Spring   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java – 如何知道在spring项目中加载bean的资源.大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我是Spring框架的新手.我想知道加载bean时引用的xml文件列表.

通过编写ApplicationContextAware类,我可以查看bean列表:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/sample-TESTContext.xml")

public class SampleClass implements ApplicationContextAware {
    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void testMethod() {

        for (String beAnname : applicationContext.getBeanDeFinitionNames()) {
            System.out.println("BeAnname " + beanName);
        }
    }
}

但我想知道bean的加载配置文件.

说“sample-TESTContext.xml”包含

http://www.springframework.org/scheR_190_11845@a/beans" xmlns:xsi="http://www.w3.org/2001/XMLscheR_190_11845@a-instance" xmlns:context="http://www.springframework.org/scheR_190_11845@a/context" xmlns:util="http://www.springframework.org/scheR_190_11845@a/util" xsi:scheR_190_11845@aLOCATIOn="http://www.springframework.org/scheR_190_11845@a/beans http://www.springframework.org/scheR_190_11845@a/beans/spring-beans-3.0.xsd
        http://www.springframework.org/scheR_190_11845@a/context http://www.springframework.org/scheR_190_11845@a/context/spring-context-3.0.xsd
        http://camel.apache.org/scheR_190_11845@a/spring http://camel.apache.org/scheR_190_11845@a/spring/camel-spring.xsd
        http://www.springframework.org/scheR_190_11845@a/util http://www.springframework.org/scheR_190_11845@a/util/spring-util-3.0.xsd">


    

我想知道加载bean的文件名列表为“sample-testOneMorecontext.xml”和“sample-TESTContext.xml”.

最佳答案
你为什么要这样做呢?我不确定内部实现是否在上下文加载后保留了该信息的记录.但是,有一种方法可以知道特定bean已从哪个资源加载.如果您有几个具有相名称的bean定义并且您想知道哪个具有“赢”,那么这将非常有用.

收回你的例子(顺便说一句,你不需要实现ApplicationContextAware,因为你自动装配它)

@ContextConfiguration
@ContextConfiguration("classpath:spring/sample-TESTContext.xml")
public class SampleTest {

    @Autowired
    private ConfigurableApplicationContext context;

    @Test
    public void foo() {
        ConfigurableListablebeanfactory beanfactory = context.getbeanfactory();
        for (String beAnname : context.getBeanDeFinitionNames()) {
            System.out.println(beAnname + " --> "+  beanfactory.getBeanDeFinition(beanName).getresourceDescription());
        }
    }
}

这给你类似的东西(不包括认实现可以自动注册的内部后处理器bean定义)

beanFirst --> class org.SampleTest$Config
beanSecond --> class path resource [foobar.xml]

其中beanFirst是从测试的内部类(称为Config)加载的,而beanSecond是从类路径根目录中名为foobar.xml的文件加载的.

大佬总结

以上是大佬教程为你收集整理的java – 如何知道在spring项目中加载bean的资源.全部内容,希望文章能够帮你解决java – 如何知道在spring项目中加载bean的资源.所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。