【问题标题】:Bean Names are being returned in String Format, Call methods or use variables of such beanBean 名称以字符串格式返回,调用方法或使用此类 bean 的变量
【发布时间】: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

标签: java spring


【解决方案1】:

你真的不想在生产代码中这样做,但我假设你只是在学习。

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

【讨论】:

  • 是的,我同意这在生产环境中是不可接受的。但我的问题是我让我们假设 3 个类实现了与国家相同的接口。和 2 个 bean 定义,其中可以是任何类类型。现在引入这些 bean,我想调用这些 bean 的实例方法? .如果说 bean 是 10,那么对于每个 bean,我都想对其进行迭代。怎么办?请帮忙
【解决方案2】:

你可以像这样得到预期的bean

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

然后调用你想要的方法就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多