下面列出了org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
@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());
}
@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);
}
@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);
}
@Test
public void testParse() throws Exception {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
reader.loadBeanDefinitions(CONTEXT);
assertTrue(beanFactory.containsBeanDefinition("testPointcut"));
}
/**
* 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;
}
@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());
}
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"));
}
@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());
}
@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);
}
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();
}
/**
* 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;
}
/**
* {@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);
}
}
}
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);
}
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);
}
/**
* 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;
}
@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());
}
private void readBeans(Resource beanResource) {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
applicationContext);
reader.loadBeanDefinitions(beanResource);
}
private void loadBeanDefinitions(String fileName) {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.appContext);
Resource resource = new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
reader.loadBeanDefinitions(resource);
this.appContext.refresh();
}
/**
* 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);
}
}