【发布时间】:2018-09-05 16:19:16
【问题描述】:
我正在借助以下功能将正在加载到容器中的 bean 带来。我从这个 SO 问题中得到了这个:Getting all beans in context。
Arrays.asList(context.getBeanDefinitionNames())
这会将 bean 名称作为列表返回给我,如下所示
[helloWorld, helloWorld2, helloRandomCountry, beforeAfterPrint]
bean 配置文件快照如下
<bean id = "helloWorld" class = "com.springspp.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
<bean id = "helloWorld2" class = "com.springspp.HelloWorld">
<property name = "message" value = "Hello Hello World!"/>
</bean>
<bean id="helloRandomCountry"
class="com.springspp.countries.HelloJapan"/>
<bean id = "beforeAfterPrint" class =
"com.springspp.BeforeAfterPrint">
</bean>
现在我有一份这些 bean 的列表,它们采用 STRING 格式。如果我想调用该类中的任何方法或使用该类中定义的任何变量,我该怎么做。我在 Stack Overflow 中检查了相关问题和相关问题,但没有找到任何答案。
典型用例如下。我想找出变量
国家
在元数据文件中配置为 helloRandomCountry 的以下类作为其 bean 名称,如上所示
class HelloJapan implements Countries{
String country="Japan";
private String thisClassString="Hello this is Japan";
public void displayString() {
System.out.println(thisClassString);
}
}
【问题讨论】:
-
通常不需要直接通过spring上下文访问一个bean。相反,让 spring 将 bean 注入到依赖它们的类中。
-
使用
@Autowire。