/**
   * Load the application context using a single classloader
   *
   * @param ac The spring application context
   * @param config a list of configurations represented as List of resources
   * @param loader the classloader to use
   */
  public void loadComponent(
      ConfigurableApplicationContext ac, List<Resource> config, ClassLoader loader) {
    ClassLoader current = Thread.currentThread().getContextClassLoader();

    Thread.currentThread().setContextClassLoader(loader);

    try {

      // make a reader
      XmlBeanDefinitionReader reader =
          new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory());

      // In Spring 2, classes aren't loaded during bean parsing unless
      // this
      // classloader property is set.
      reader.setBeanClassLoader(loader);

      reader.loadBeanDefinitions(config.toArray(new Resource[0]));
    } catch (Throwable t) {
      log.warn("loadComponentPackage: exception loading: " + config + " : " + t, t);
    } finally {
      // restore the context loader
      Thread.currentThread().setContextClassLoader(current);
    }
  }
  /** Tests where the static factory method is on a different class. */
  @Test
  public void testFactoryMethodsOnExternalClass() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs"));
    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs"));
    String[] names = xbf.getBeanNamesForType(TestBean.class);
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs"));
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs"));

    TestBean tb = (TestBean) xbf.getBean("externalFactoryMethodWithoutArgs");
    assertEquals(2, tb.getAge());
    assertEquals("Tristan", tb.getName());
    tb = (TestBean) xbf.getBean("externalFactoryMethodWithArgs");
    assertEquals(33, tb.getAge());
    assertEquals("Rod", tb.getName());

    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs"));
    assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs"));
    names = xbf.getBeanNamesForType(TestBean.class);
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs"));
    assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs"));
  }
 private void loadBeanDefinitions(String fileName) {
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
   ClassPathResource resource =
       new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
   reader.loadBeanDefinitions(resource);
   appContext.refresh();
 }
 /**
  * Overriden superclass method. Creates a single application context containing all the service
  * beans
  *
  * @throws PlatformException
  */
 protected void loadServiceContexts() throws PlatformException {
   // locate and load the individual service bean XML files using the common batch beans context as
   // parent
   File[] serviceBeansFiles =
       FileLocator.findFiles(ServiceFrameworkConstants.SPRING_SERVICES_CONFIG);
   List<String> fileNamesList = new LinkedList<String>();
   for (File serviceBeansFile : serviceBeansFiles) {
     // dont load the individual service context, just register an empty context for display
     // purposes
     GenericApplicationContext nonRefreshedServiceContext = new GenericApplicationContext();
     XmlBeanDefinitionReader beanDefReader =
         new XmlBeanDefinitionReader(nonRefreshedServiceContext);
     // add the "file:" prefix to file names to explicitly state that it is on the file system and
     // not a classpath resource
     beanDefReader.loadBeanDefinitions(
         ServiceConfigInfo.FILE_PREFIX + serviceBeansFile.getAbsolutePath());
     ServiceConfigInfo nonInitedServiceConfigInfo =
         new ServiceConfigInfo(serviceBeansFile, null, nonRefreshedServiceContext);
     super.registerServiceContext(nonInitedServiceConfigInfo);
     // add the "file:" prefix to file names to get around strange behavior of
     // FileSystemXmlApplicationContext that converts absolute path to relative path
     fileNamesList.add(ServiceConfigInfo.FILE_PREFIX + serviceBeansFile.getAbsolutePath());
   }
   this.servicesContext =
       new FileSystemXmlApplicationContext(
           (String[]) fileNamesList.toArray(new String[0]),
           SpringServicesContainer.getCommonServiceBeansContext());
   super.registerServiceContext(
       new ServiceConfigInfo(
           new File(ServiceFrameworkConstants.SPRING_SERVICES_CONFIG),
           null,
           this.servicesContext));
 }
 private void loadBeanDefinitions(String fileName) {
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.appContext);
   ClassPathResource resource =
       new ClassPathResource(fileName, MessageBrokerBeanDefinitionParserTests.class);
   reader.loadBeanDefinitions(resource);
   this.appContext.refresh();
 }
  @Test
  public void parseInternal_withMinimalConfig_shouldCreateDefaultTemplate() throws Exception {
    // Arrange
    DefaultListableBeanFactory registry = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);

    // Act
    reader.loadBeanDefinitions(
        new ClassPathResource(getClass().getSimpleName() + "-minimal.xml", getClass()));

    // Assert
    NotificationMessagingTemplate notificationMessagingTemplate =
        registry.getBean(NotificationMessagingTemplate.class);
    assertSame(
        registry.getBean(AmazonSNSClient.class),
        ReflectionTestUtils.getField(notificationMessagingTemplate, "amazonSns"));

    Object cachingDestinationResolverProxy =
        ReflectionTestUtils.getField(notificationMessagingTemplate, "destinationResolver");
    Object targetDestinationResolver =
        ReflectionTestUtils.getField(cachingDestinationResolverProxy, "targetDestinationResolver");
    assertEquals(
        registry.getBean(GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME),
        ReflectionTestUtils.getField(targetDestinationResolver, "resourceIdResolver"));

    assertTrue(
        StringMessageConverter.class.isInstance(
            notificationMessagingTemplate.getMessageConverter()));
    assertEquals(
        String.class,
        ReflectionTestUtils.getField(
            notificationMessagingTemplate.getMessageConverter(), "serializedPayloadClass"));
  }
  @Before
  public void setUp() throws Exception {
    // reset counter just to be sure
    DummyListener.BIND_CALLS = 0;
    DummyListener.UNBIND_CALLS = 0;

    DummyListenerServiceSignature.BIND_CALLS = 0;
    DummyListenerServiceSignature.UNBIND_CALLS = 0;

    DummyListenerServiceSignature2.BIND_CALLS = 0;
    DummyListenerServiceSignature2.UNBIND_CALLS = 0;

    BundleContext bundleContext =
        new MockBundleContext() {
          // service reference already registered
          public ServiceReference[] getServiceReferences(String clazz, String filter)
              throws InvalidSyntaxException {
            return new ServiceReference[] {
              new MockServiceReference(new String[] {Cloneable.class.getName()})
            };
          }
        };

    appContext = new GenericApplicationContext();
    appContext
        .getBeanFactory()
        .addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
    appContext.setClassLoader(getClass().getClassLoader());

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    // reader.setEventListener(this.listener);
    reader.loadBeanDefinitions(
        new ClassPathResource("osgiReferenceNamespaceHandlerTests.xml", getClass()));
    appContext.refresh();
  }
  @Test
  public void testFactoryMethodsSingletonOnTargetClass() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    TestBean tb = (TestBean) xbf.getBean("defaultTestBean");
    assertEquals("defaultInstance", tb.getName());
    assertEquals(1, tb.getAge());

    FactoryMethods fm = (FactoryMethods) xbf.getBean("default");
    assertEquals(0, fm.getNum());
    assertEquals("default", fm.getName());
    assertEquals("defaultInstance", fm.getTestBean().getName());
    assertEquals("setterString", fm.getStringValue());

    fm = (FactoryMethods) xbf.getBean("testBeanOnly");
    assertEquals(0, fm.getNum());
    assertEquals("default", fm.getName());
    // This comes from the test bean
    assertEquals("Juergen", fm.getTestBean().getName());

    fm = (FactoryMethods) xbf.getBean("full");
    assertEquals(27, fm.getNum());
    assertEquals("gotcha", fm.getName());
    assertEquals("Juergen", fm.getTestBean().getName());

    FactoryMethods fm2 = (FactoryMethods) xbf.getBean("full");
    assertSame(fm, fm2);

    xbf.destroySingletons();
    assertTrue(tb.wasDestroyed());
  }
 @Override
 protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
   this.registeredComponents = new HashSet<ComponentDefinition>();
   beanDefinitionReader.setEventListener(
       new StoringReaderEventListener(this.registeredComponents));
   beanDefinitionReader.setSourceExtractor(new PassThroughSourceExtractor());
 }
 @Before
 public void setUp() throws Exception {
   this.beanFactory = new DefaultListableBeanFactory();
   this.beanFactory.registerScope("request", new RequestScope());
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
   reader.loadBeanDefinitions(new ClassPathResource("requestScopedProxyTests.xml", getClass()));
   this.beanFactory.preInstantiateSingletons();
 }
 @Before
 public void setUp() throws Exception {
   beanFactory = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
   reader.loadBeanDefinitions(
       new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
 }
 /**
  * Load the springified server configuration.
  *
  * @return
  */
 protected ApplicationContext loadServerApplicationContext(File configFile)
     throws SiteWhereException {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
   reader.loadBeanDefinitions(new FileSystemResource(configFile));
   context.refresh();
   return context;
 }
  /**
   * Will parse the module xml definition file, looking for "${foo}" placeholders and advertise a
   * {@link ModuleOption} for each of those.
   *
   * <p>Note that this may end up in false positives and does not convey much information.
   *
   * @param classLoaderToUse
   */
  private ModuleOptionsMetadata inferModuleOptionsMetadata(
      ModuleDefinition definition, ClassLoader classLoaderToUse) {
    final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    reader.setResourceLoader(new PathMatchingResourcePatternResolver(classLoaderToUse));
    reader.loadBeanDefinitions(definition.getResource());

    return defaultModuleOptionsMetadataCollector.collect(beanFactory);
  }
 public void testWithInputSourceAndExplicitValidationMode() {
   SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
   ;
   InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml"));
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);
   reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_DTD);
   reader.loadBeanDefinitions(resource);
   testBeanDefinitions(registry);
 }
  @Test
  public void testPrivateFactoryMethod() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    TestBean tb = (TestBean) xbf.getBean("defaultTestBean.private");
    assertEquals(1, tb.getAge());
  }
  @BeforeClass
  public static void prepare() throws Exception // NOPMD
      {
    Registry.activateStandaloneMode();
    Utilities.setJUnitTenant();
    LOG.debug("Preparing...");

    final ApplicationContext appCtx = Registry.getGlobalApplicationContext();

    assertTrue(
        "Application context of type "
            + appCtx.getClass()
            + " is not a subclass of "
            + ConfigurableApplicationContext.class,
        appCtx instanceof ConfigurableApplicationContext);

    final ConfigurableApplicationContext applicationContext =
        (ConfigurableApplicationContext) appCtx;
    final ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
    assertTrue(
        "Bean Factory of type "
            + beanFactory.getClass()
            + " is not of type "
            + BeanDefinitionRegistry.class,
        beanFactory instanceof BeanDefinitionRegistry);
    final XmlBeanDefinitionReader xmlReader =
        new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test.xml"));
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/merchandisefulfilmentprocess-spring-test-fraudcheck.xml"));
    xmlReader.loadBeanDefinitions(
        new ClassPathResource(
            "/merchandisefulfilmentprocess/test/process/order-process-spring.xml"));
    modelService = (ModelService) getBean("modelService");
    processService = (DefaultBusinessProcessService) getBean("businessProcessService");
    definitonFactory = processService.getProcessDefinitionFactory();

    LOG.warn("Prepare Process Definition factory...");
    definitonFactory.add(
        "classpath:/merchandisefulfilmentprocess/test/process/payment-process.xml");

    // setup command factory to mock
    final DefaultCommandFactoryRegistryImpl commandFactoryReg =
        appCtx.getBean(DefaultCommandFactoryRegistryImpl.class);
    commandFactoryReg.setCommandFactoryList(
        Arrays.asList((CommandFactory) appCtx.getBean("mockupCommandFactory")));

    taskServiceStub = appCtx.getBean(TaskServiceStub.class);
    productService = appCtx.getBean("defaultProductService", DefaultProductService.class);
    cartService = appCtx.getBean("defaultCartService", DefaultCartService.class);
    userService = appCtx.getBean("defaultUserService", DefaultUserService.class);
  }
  @Test
  public void testFactoryMethodForJavaMailSession() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    MailSession session = (MailSession) xbf.getBean("javaMailSession");
    assertEquals("someuser", session.getProperty("mail.smtp.user"));
    assertEquals("somepw", session.getProperty("mail.smtp.password"));
  }
 @Test
 public void testLazyInitFalse() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitFalseTests.xml");
   assertFalse(
       "lazy-init should be false", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit());
   assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT);
   context.refresh();
   assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT);
 }
 @Test
 public void testAutowireNo() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireNoTests.xml");
   context.refresh();
   DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
   assertNull("no dependencies should have been autowired", bean.getConstructorDependency());
   assertNull("no dependencies should have been autowired", bean.getPropertyDependency1());
   assertNull("no dependencies should have been autowired", bean.getPropertyDependency2());
 }
  @Test
  public void testFactoryMethodsWithAutowire() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    FactoryMethods fm = (FactoryMethods) xbf.getBean("fullWithAutowire");
    assertEquals(27, fm.getNum());
    assertEquals("gotchaAutowired", fm.getName());
    assertEquals("Juergen", fm.getTestBean().getName());
  }
 @Test
 public void testDefaultInitAndDestroyMethodsDefined() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultInitAndDestroyMethodsTests.xml");
   context.refresh();
   DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
   assertTrue("bean should have been initialized", bean.isInitialized());
   context.close();
   assertTrue("bean should have been destroyed", bean.isDestroyed());
 }
 @Test
 public void testDependencyCheckAll() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultDependencyCheckAllTests.xml");
   try {
     context.refresh();
     fail("expected exception due to dependency check");
   } catch (UnsatisfiedDependencyException e) {
     // expected
   }
 }
 @Test
 public void testAutowireByType() {
   GenericApplicationContext context = new GenericApplicationContext();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
   reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireByTypeTests.xml");
   try {
     context.refresh();
     fail("expected exception due to multiple matches for byType autowiring");
   } catch (UnsatisfiedDependencyException e) {
     // expected
   }
 }
 @Test
 public void testFactoryMethodNoMatchingStaticMethod() {
   DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
   reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
   try {
     xbf.getBean("noMatchPrototype");
     fail("No static method matched");
   } catch (BeanCreationException ex) {
     // Ok
   }
 }
 @Test
 public void testCannotSpecifyFactoryMethodArgumentsOnSingleton() {
   DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
   XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
   reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
   try {
     xbf.getBean("testBeanOnly", new TestBean());
     fail("Shouldn't allow args to be passed to a singleton");
   } catch (BeanDefinitionStoreException ex) {
     // OK
   }
 }
  @Test
  public void testFactoryMethodsWithInvalidDestroyMethod() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

    try {
      xbf.getBean("defaultTestBeanWithInvalidDestroyMethod");
      fail("Should have thrown BeanCreationException");
    } catch (BeanCreationException ex) {
      // expected
    }
  }
  /**
   * called before @BeforeTransaction methods
   *
   * @see
   *     org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext)
   */
  @Override
  public void prepareTestInstance(TestContext testContext) throws Exception {
    StartModule startModuleAnnotation = testContext.getTestClass().getAnnotation(StartModule.class);

    // if the developer listed some modules with the @StartModule annotation on the class
    if (startModuleAnnotation != null) {

      if (!lastClassRun.equals(testContext.getTestClass().getSimpleName())) {
        // mark this with our class so that the services are only restarted once
        lastClassRun = testContext.getTestClass().getSimpleName();

        if (!Context.isSessionOpen()) Context.openSession();

        // load the omods that the dev defined for this class
        String modulesToLoad = StringUtils.join(startModuleAnnotation.value(), " ");

        Properties props = BaseContextSensitiveTest.runtimeProperties;
        props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD, modulesToLoad);
        try {
          ModuleUtil.startup(props);
        } catch (Exception e) {
          System.out.println("Error while starting modules: ");
          e.printStackTrace(System.out);
          throw e;
        }
        Assert.assertTrue(
            "Some of the modules did not start successfully for "
                + testContext.getTestClass().getSimpleName()
                + ". Only "
                + ModuleFactory.getStartedModules().size()
                + " modules started instead of "
                + startModuleAnnotation.value().length,
            startModuleAnnotation.value().length <= ModuleFactory.getStartedModules().size());

        /*
         * Refresh spring so the Services are recreated (aka serializer gets put into the SerializationService)
         * To do this, wrap the applicationContext from the testContext into a GenericApplicationContext, allowing
         * loading beans from moduleApplicationContext into it and then calling ctx.refresh()
         * This approach ensures that the application context remains consistent
         */
        GenericApplicationContext ctx =
            new GenericApplicationContext(testContext.getApplicationContext());
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("moduleApplicationContext.xml"));
        ctx.refresh();

        // session is closed by the test framework
        // Context.closeSession();
      }
    }
  }
  /**
   * Load the template BeanDefinition and call {@link #transform(ConfigurableListableBeanFactory,
   * BeanDefinition, Element, ParserContext)} to apply runtime configuration value to it. <code>
   * builder</code> will be configured to instantiate the bean in the Spring context that we are
   * parsing.
   *
   * <p>During parsing, an instance of {@link
   * TemplateBeanDefinitionParser.TemplateComponentDefinition} is pushed onto <code>ParserContext
   * </code> so that nested tags can access the enclosing template configuration with a call to
   * {@link #findEnclosingTemplateFactory(ParserContext)}. Subclasses can override {@link
   * #newComponentDefinition(String, Object, DefaultListableBeanFactory)} to provide a subclass of
   * {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} to the parser context if
   * necessary.
   */
  @Override
  protected final void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    // if we have multiple nested bean definitions, we only parse the template factory
    // once.  this allows configuration changes made by enclosing bean parsers to be inherited
    // by contained beans, which is quite useful.
    DefaultListableBeanFactory templateFactory = findEnclosingTemplateFactory(parserContext);
    TemplateComponentDefinition tcd = null;
    if (templateFactory == null) {

      // no nesting -- load the template XML configuration from the classpath.
      final BeanFactory parentFactory = (BeanFactory) parserContext.getRegistry();
      templateFactory = new DefaultListableBeanFactory(parentFactory);

      // load template bean definitions
      DefaultResourceLoader loader = new DefaultResourceLoader();
      XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(templateFactory);
      reader.setResourceLoader(loader);
      reader.setEntityResolver(new ResourceEntityResolver(loader));
      reader.loadBeanDefinitions(templateResource);

      // propagate factory post-processors from the source factory into the template
      // factory.
      BeanDefinition ppChain = new RootBeanDefinition(ChainingBeanFactoryPostProcessor.class);
      ppChain.getPropertyValues().addPropertyValue("targetFactory", templateFactory);
      parserContext.getReaderContext().registerWithGeneratedName(ppChain);

      // push component definition onto the parser stack for the benefit of
      // nested bean definitions.
      tcd =
          newComponentDefinition(
              element.getNodeName(), parserContext.extractSource(element), templateFactory);
      parserContext.pushContainingComponent(tcd);
    }

    try {
      // allow subclasses to apply overrides to the template bean definition.
      BeanDefinition def = templateFactory.getBeanDefinition(templateId);
      transform(templateFactory, def, element, parserContext);

      // setup our factory bean to instantiate the modified bean definition upon request.
      builder.addPropertyValue("beanFactory", templateFactory);
      builder.addPropertyValue("beanName", templateId);
      builder.getRawBeanDefinition().setAttribute("id", def.getAttribute("id"));

    } finally {
      if (tcd != null) parserContext.popContainingComponent();
    }
  }
  /**
   * Load one component package into the AC
   *
   * @param packageRoot The file path to the component package
   * @param ac The ApplicationContext to load into
   */
  protected void loadComponentPackage(File dir, ConfigurableApplicationContext ac) {
    // setup the classloader onto the thread
    ClassLoader current = Thread.currentThread().getContextClassLoader();
    ClassLoader loader = newPackageClassLoader(dir);

    M_log.info("loadComponentPackage: " + dir);

    Thread.currentThread().setContextClassLoader(loader);

    File xml = null;

    try {
      // load this xml file
      File webinf = new File(dir, "WEB-INF");
      xml = new File(webinf, "components.xml");

      // make a reader
      XmlBeanDefinitionReader reader =
          new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory());

      // In Spring 2, classes aren't loaded during bean parsing unless this
      // classloader property is set.
      reader.setBeanClassLoader(loader);

      List<Resource> beanDefList = new ArrayList<Resource>();
      beanDefList.add(new FileSystemResource(xml.getCanonicalPath()));

      // Load the demo components, if necessary
      File demoXml = new File(webinf, "components-demo.xml");
      if ("true".equalsIgnoreCase(System.getProperty("sakai.demo"))) {
        if (M_log.isDebugEnabled()) M_log.debug("Attempting to load demo components");
        if (demoXml.exists()) {
          if (M_log.isInfoEnabled()) M_log.info("Loading demo components from " + dir);
          beanDefList.add(new FileSystemResource(demoXml.getCanonicalPath()));
        }
      } else {
        if (demoXml.exists()) {
          // Only log that we're skipping the demo components if they exist
          if (M_log.isInfoEnabled()) M_log.info("Skipping demo components from " + dir);
        }
      }

      reader.loadBeanDefinitions(beanDefList.toArray(new Resource[0]));
    } catch (Exception e) {
      M_log.warn("loadComponentPackage: exception loading: " + xml + " : " + e, e);
    } finally {
      // restore the context loader
      Thread.currentThread().setContextClassLoader(current);
    }
  }
  /** @param args */
  public static void main(String[] args) {

    final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    // reader.setValidating(false);

    reader.loadBeanDefinitions(new ClassPathResource("spring-container.xml"));

    BeanFactoryContainer.LOGGER.info("   Bean definitions loaded ");

    final Employee employee = (Employee) beanFactory.getBean("employee");

    BeanFactoryContainer.LOGGER.info("Employee  :  " + employee);
  }