下面演示如何使用bean名称获取配置源。
-
获取bean的bean定义:
ctx.getBeanDefinition(“beanName”)
-
援引
获取资源描述()
.
下面是一个工作示例,它设置了在AppConfig中定义的名为“a”的基于@Configuration的bean,以及在SpringBeans.XML中定义名为“xmlBean”的XML bean。在每种情况下,源@Configuration类或xml文件都会正确显示。
这里是java配置类,它设置bean=a,并加载XML配置文件SpringBeans。xml包含bean=xmlBean。
@Configuration
@ImportResource({"classpath:SpringBeans.xml"})
@ComponentScan(basePackages = "com.test.config")
public class AppConfig {
@Bean
public A a() {
return new A();
}
}
下面是SpringBeans.xml中定义的bean:
<bean id="xmlBean" class="com.test.HelloWorld">
<property name="name" value="XML" />
</bean>
下面是使用getResourceDescription()的简单代码:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
BeanDefinition javaConfigBeanDefinition = ctx.getBeanDefinition("a");
System.out.println("Creation class for a=" + javaConfigBeanDefinition.getResourceDescription());
BeanDefinition xmlBeanDefinition = ctx.getBeanDefinition("xmlBean");
System.out.println("Creation XML file for xmlBean=" + xmlBeanDefinition.getResourceDescription());
输出:
Creation class for a=com.test.config.AppConfig
Creation XML file for xmlBean=class path resource [SpringBeans.xml]
可能更实际的方法是创建
BeanDefinitionRegistryPostProcessor(beanDefinition注册后处理器)
并在那里请求信息:
@Component
public class FindBeanConfigLocation implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition javaConfigBeanDefinition = registry.getBeanDefinition("a");
System.out.println("Creation class for a=" + javaConfigBeanDefinition.getResourceDescription());
BeanDefinition xmlBeanDefinition = registry.getBeanDefinition("xmlBean");
System.out.println("Creation XML file for xmlBean=" + xmlBeanDefinition.getResourceDescription());
}
}