Java Code Examples for org.springframework.beans.factory.xml.xmlbeandefinitionreader#loadBeanDefinitions()

The following examples show how to use org.springframework.beans.factory.xml.xmlbeandefinitionreader#loadBeanDefinitions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassPathXmlApplicationContextTests.java    From spring4-understanding with Apache License 2.0 7 votes vote down vote up
@Test
public void testGenericApplicationContextWithXmlBeanDefinitionsAndClassLoaderNull() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setClassLoader(null);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
	reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_B, getClass()));
	reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_C, getClass()));
	reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_A, getClass()));
	ctx.refresh();
	assertEquals(ObjectUtils.identityToString(ctx), ctx.getId());
	assertEquals(ObjectUtils.identityToString(ctx), ctx.getDisplayName());
	assertTrue(ctx.containsBean("service"));
	assertTrue(ctx.containsBean("logicOne"));
	assertTrue(ctx.containsBean("logicTwo"));
	ctx.close();
}
 
Example 2
Source File: SimpleScopeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	beanFactory = new DefaultListableBeanFactory();
	Scope scope = new NoOpScope() {
		private int index;
		private List<TestBean> objects = new LinkedList<TestBean>(); {
			objects.add(new TestBean());
			objects.add(new TestBean());
		}
		@Override
		public Object get(String name, ObjectFactory<?> objectFactory) {
			if (index >= objects.size()) {
				index = 0;
			}
			return objects.get(index++);
		}
	};

	beanFactory.registerScope("myScope", scope);

	String[] scopeNames = beanFactory.getRegisteredScopeNames();
	assertEquals(1, scopeNames.length);
	assertEquals("myScope", scopeNames[0]);
	assertSame(scope, beanFactory.getRegisteredScope("myScope"));

	XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(beanFactory);
	xbdr.loadBeanDefinitions(CONTEXT);
}
 
Example 3
Source File: SQLErrorCodesFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new instance of the {@link SQLErrorCodesFactory} class.
 * <p>Not public to enforce Singleton design pattern. Would be private
 * except to allow testing via overriding the
 * {@link #loadResource(String)} method.
 * <p><b>Do not subclass in application code.</b>
 * @see #loadResource(String)
 */
protected SQLErrorCodesFactory() {
	Map<String, SQLErrorCodes> errorCodes;

	try {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		lbf.setBeanClassLoader(getClass().getClassLoader());
		XmlBeanDefinitionReader bdr = new XmlBeanDefinitionReader(lbf);

		// Load default SQL error codes.
		Resource resource = loadResource(SQL_ERROR_CODE_DEFAULT_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
		}
		else {
			logger.info("Default sql-error-codes.xml not found (should be included in spring-jdbc jar)");
		}

		// Load custom SQL error codes, overriding defaults.
		resource = loadResource(SQL_ERROR_CODE_OVERRIDE_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
			logger.debug("Found custom sql-error-codes.xml file at the root of the classpath");
		}

		// Check all beans of type SQLErrorCodes.
		errorCodes = lbf.getBeansOfType(SQLErrorCodes.class, true, false);
		if (logger.isTraceEnabled()) {
			logger.trace("SQLErrorCodes loaded: " + errorCodes.keySet());
		}
	}
	catch (BeansException ex) {
		logger.warn("Error loading SQL error codes from config file", ex);
		errorCodes = Collections.emptyMap();
	}

	this.errorCodesMap = errorCodes;
}
 
Example 4
Source File: ExtensibleXmlAuthoringDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        // 创建 IoC 底层容器
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 创建 XML 资源的 BeanDefinitionReader
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        // 记载 XML 资源
        reader.loadBeanDefinitions("META-INF/users-context.xml");
        // 获取 User Bean 对象
        User user = beanFactory.getBean(User.class);
        System.out.println(user);
    }
 
Example 5
Source File: SpringCamelContextBootstrap.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private void loadBeanDefinitions(Resource resource, ClassLoader classLoader) {
    applicationContext = new GenericApplicationContext();
    applicationContext.setClassLoader(classLoader);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext) {
        @Override
        protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
            NamespaceHandlerResolver defaultResolver = super.createDefaultNamespaceHandlerResolver();
            return new SpringCamelContextBootstrap.CamelNamespaceHandlerResolver(defaultResolver);
        }
    };
    xmlReader.loadBeanDefinitions(resource);
}
 
Example 6
Source File: SpringMetadataProviderImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
public synchronized void initializeMetadata(Collection<Class<?>> types) {
	// First, extract the data from the spring configuration into a form usable by the Spring XML parser
	if (LOG.isDebugEnabled()) {
		LOG.debug("Loading Metadata Bean Definitions from Locations:");
		for (String loc : resourceLocations) {
			LOG.debug(loc);
		}
	}
	// Now, parse the beans and load them into the bean factory
	XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beanFactory);
	String configFileLocationsArray[] = new String[resourceLocations.size()];
	configFileLocationsArray = resourceLocations.toArray(configFileLocationsArray);
	xmlReader.loadBeanDefinitions(configFileLocationsArray);

	// extract the objects from the bean factory, by pulling all the DataObjectMetadata objects
	Map<String, DataObjectMetadata> metadataObjects = beanFactory.getBeansOfType(DataObjectMetadata.class);
	if (LOG.isInfoEnabled()) {
		LOG.info(metadataObjects.size() + " DataObjectMetadata objects in Spring configuration files");
	}
	// populate the map
	masterMetadataMap.clear();
	for (DataObjectMetadata metadata : metadataObjects.values()) {
		if (metadata.getType() != null) {
			if (metadata instanceof DataObjectMetadataImpl) {
				((DataObjectMetadataImpl) metadata).setProviderName(this.getClass().getSimpleName());
			}
			masterMetadataMap.put(metadata.getType(), metadata);
		} else {
			LOG.error("Configuration Error.  MetadataObject in the Spring context contained a null DataObjectType reference: "
					+ metadata);
		}
	}
}
 
Example 7
Source File: XmlViewResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize the view bean factory from the XML file.
 * Synchronized because of access by parallel threads.
 * @throws BeansException in case of initialization errors
 */
protected synchronized BeanFactory initFactory() throws BeansException {
	if (this.cachedFactory != null) {
		return this.cachedFactory;
	}

	Resource actualLocation = this.location;
	if (actualLocation == null) {
		actualLocation = getApplicationContext().getResource(DEFAULT_LOCATION);
	}

	// Create child ApplicationContext for views.
	GenericWebApplicationContext factory = new GenericWebApplicationContext();
	factory.setParent(getApplicationContext());
	factory.setServletContext(getServletContext());

	// Load XML resource with context-aware entity resolver.
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
	reader.setEnvironment(getApplicationContext().getEnvironment());
	reader.setEntityResolver(new ResourceEntityResolver(getApplicationContext()));
	reader.loadBeanDefinitions(actualLocation);

	factory.refresh();

	if (isCache()) {
		this.cachedFactory = factory;
	}
	return factory;
}
 
Example 8
Source File: MessageBrokerBeanDefinitionParserTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void loadBeanDefinitions(String fileName) {
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.appContext);
	ClassPathResource resource = new ClassPathResource(fileName, MessageBrokerBeanDefinitionParserTests.class);
	reader.loadBeanDefinitions(resource);
	this.appContext.setServletContext(new MockServletContext());
	this.appContext.refresh();
}
 
Example 9
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDefaultInitAndDestroyMethodsNotDefined() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml");
	context.refresh();
	DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
	assertFalse("bean should not have been initialized", bean.isInitialized());
	context.close();
	assertFalse("bean should not have been destroyed", bean.isDestroyed());
}
 
Example 10
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDefaultAutowire() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.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());
}
 
Example 11
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDefaultDependencyCheck() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml");
	context.refresh();
	DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
	assertNull("constructor dependency should not have been autowired", bean.getConstructorDependency());
	assertNull("property dependencies should not have been autowired", bean.getPropertyDependency1());
	assertNull("property dependencies should not have been autowired", bean.getPropertyDependency2());
}
 
Example 12
Source File: App1.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ClassPathResource resource = new ClassPathResource("beans.xml");
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
	reader.loadBeanDefinitions(resource);

	HelloBean helloBean = (HelloBean) factory.getBean("hello");
	System.out.println(helloBean.hello("hello world1"));

}
 
Example 13
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultNonExistingInitAndDestroyMethodsDefined() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultNonExistingInitAndDestroyMethodsTests.xml");
	context.refresh();
	DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME);
	assertFalse("bean should not have been initialized", bean.isInitialized());
	context.close();
	assertFalse("bean should not have been destroyed", bean.isDestroyed());
}
 
Example 14
Source File: SQLErrorCodesFactory.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of the {@link SQLErrorCodesFactory} class.
 * <p>Not public to enforce Singleton design pattern. Would be private
 * except to allow testing via overriding the
 * {@link #loadResource(String)} method.
 * <p><b>Do not subclass in application code.</b>
 * @see #loadResource(String)
 */
protected SQLErrorCodesFactory() {
	Map<String, SQLErrorCodes> errorCodes;

	try {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		lbf.setBeanClassLoader(getClass().getClassLoader());
		XmlBeanDefinitionReader bdr = new XmlBeanDefinitionReader(lbf);

		// Load default SQL error codes.
		Resource resource = loadResource(SQL_ERROR_CODE_DEFAULT_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
		}
		else {
			logger.warn("Default sql-error-codes.xml not found (should be included in spring.jar)");
		}

		// Load custom SQL error codes, overriding defaults.
		resource = loadResource(SQL_ERROR_CODE_OVERRIDE_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
			logger.info("Found custom sql-error-codes.xml file at the root of the classpath");
		}

		// Check all beans of type SQLErrorCodes.
		errorCodes = lbf.getBeansOfType(SQLErrorCodes.class, true, false);
		if (logger.isInfoEnabled()) {
			logger.info("SQLErrorCodes loaded: " + errorCodes.keySet());
		}
	}
	catch (BeansException ex) {
		logger.warn("Error loading SQL error codes from config file", ex);
		errorCodes = Collections.emptyMap();
	}

	this.errorCodesMap = errorCodes;
}
 
Example 15
Source File: TopLevelAopTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse() throws Exception {
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
	reader.loadBeanDefinitions(CONTEXT);

	assertTrue(beanFactory.containsBeanDefinition("testPointcut"));
}
 
Example 16
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testLazyInitTrue() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitTrueTests.xml");
	assertTrue("lazy-init should be true", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit());
	assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT);
	context.refresh();
	assertEquals("bean should not have been instantiated yet", 0, DefaultsTestBean.INIT_COUNT);
	context.getBean(TEST_BEAN_NAME);
	assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT);
}
 
Example 17
Source File: ComponentScanParserBeanDefinitionDefaultsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testDefaultLazyInit() {
	GenericApplicationContext context = new GenericApplicationContext();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
	reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.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);
}
 
Example 18
Source File: AnnotationDrivenBeanDefinitionParserTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void loadBeanDefinitions(String fileName) {
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.appContext);
	Resource resource = new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
	reader.loadBeanDefinitions(resource);
	this.appContext.refresh();
}
 
Example 19
Source File: EndpointCreationLoop2.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void readBeans(Resource beanResource) {
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                    applicationContext);
    reader.loadBeanDefinitions(beanResource);
}
 
Example 20
Source File: AbstractXmlApplicationContext.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Load the bean definitions with the given XmlBeanDefinitionReader.
 * <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
 * method; hence this method is just supposed to load and/or register bean definitions.
 * @param reader the XmlBeanDefinitionReader to use
 * @throws BeansException in case of bean registration errors
 * @throws IOException if the required XML document isn't found
 * @see #refreshBeanFactory
 * @see #getConfigLocations
 * @see #getResources
 * @see #getResourcePatternResolver
 */
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
	Resource[] configResources = getConfigResources();
	if (configResources != null) {
		reader.loadBeanDefinitions(configResources);
	}
	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		reader.loadBeanDefinitions(configLocations);
	}
}