Bean名称以字符串格式,调用方法或使用此类Bean的变量返回

时间:2018-09-05 16:19:16

标签: java spring

我借助以下功能将正在容器中装载的豆类带入。我是从Getting all beans in context这样的问题中得到的。

Arrays.asList(context.getBeanDefinitionNames())

这将返回我的bean名称作为列表,如下所示

  

[helloWorld,helloWorld2,helloRandomCountry,afterAfterPrint]

如下所示的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格式。如果我想调用该类中的任何方法或使用该类中定义的任何变量,该怎么做。我检查了堆栈溢出中的链接问题和相对问题,但没有找到任何答案。

典型用例如下。我想找出变量

  

国家

来自下面的类,该类在元数据文件中配置为helloRandomCountry作为其bean名称,如上所示

    class HelloJapan implements Countries{
        String country="Japan";
        private String thisClassString="Hello this is Japan";
        public void displayString() {
            System.out.println(thisClassString);
        }
    }

2 个答案:

答案 0 :(得分:0)

您确实不想在生产代码中执行此操作,但是我假设您只是在学习。

您可以致电context.getBean("beanName")。那将返回一个原始对象。因此,您需要将其强制转换为正确的对象。您可以尝试使用其他方法,但是由于它们使用相同的类类型,因此可能会遇到问题。

答案 1 :(得分:0)

您可以像这样获得期望的豆子

HelloJapan helloJapan = context.getBeansOfType(HelloJapan.class).get("helloRandomCountry");

然后在其上调用所需的方法。