gpt4 book ai didi

java - 如何知道在 spring 项目中加载 bean 的资源。

转载 作者:搜寻专家 更新时间:2023-10-31 20:11:43 24 4
gpt4 key购买 nike

我是 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”包含

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


<beans:import resource="classpath*:spring/sample-testOneMorecontext.xml"/>
</beans:beans>

我想知道从中加载 bean 的文件名列表,如“sample-testOneMorecontext.xml”和“sample-testcontext.xml”。

最佳答案

您为什么要这样做?我不确定一旦加载上下文,内部实现是否会记录该信息。但是,有一种方法可以知道特定 bean 是从哪个资源 加载的。如果您有多个具有相同名称的 bean 定义并且您想知道哪个定义“获胜”,那么这会很有用。

收回你的例子(顺便说一句,你不需要实现 ApplicationContextAware 因为你正在 Autowiring 它)

@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 从名为 的文件加载foob​​ar.xml 位于类路径的根目录中。

关于java - 如何知道在 spring 项目中加载 bean 的资源。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23215575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com