how to know resource from which a bean is loaded in spring project.

后端 未结 1 1246
南笙
南笙 2021-01-18 10:40

I am new to spring framework. I am trying to know the list of xml files that are referenced while loading the beans.

By writing a class that is ApplicationContextAwa

相关标签:
1条回答
  • 2021-01-18 11:17

    Why would you want to do that exactly? I am not sure that the internal implementation keeps a record of that information once the context has loaded. However, there is a way to know from which resource a particular bean has been loaded. That can be useful if you have several bean definitions with the same name and you want to know which one has "won".

    Taking back your example (btw, you don't need to implement ApplicationContextAware since you are autowiring it)

    @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());
            }
        }
    }
    

    This gives you something like (excluding the internal post processor bean definitions that the default implementation may register automatically)

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

    Where beanFirst was loaded from an inner class of the test (called Config) and beanSecond was loaded from a file called foobar.xml at the root of the classpath.

    0 讨论(0)
提交回复
热议问题