【问题标题】:Retrieving property/value as string from Spring bean从 Spring bean 检索属性/值作为字符串
【发布时间】:2013-07-25 21:46:47
【问题描述】:

我的 context.xml 中有以下内容:

<bean id="myBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>file:${specific.dir}/file1.properties</value>
            <value>file:${specific.dir}/file2.properties</value>
            <value>file:${specific.dir}/file3.properties</value>
            <value>file:${specific.dir}/file4.properties</value>
        </list>
    </property>
</bean>

我正在通过静态 spring 应用程序上下文在 POJO 中检索此 bean,并通过调试器,这似乎确实有效。

我是否可以检索列表中的四个值以及此 POJO 中的属性名称?

我的 staticSpringApplicationContext 如下:

public class StaticSpringApplicationContext implements ApplicationContextAware  {
private static ApplicationContext CONTEXT;

  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  public static Object getBean(String beanName) {
    return CONTEXT.getBean(beanName);
  }

}

在我的 POJO 中遵循这个:

StaticSpringApplicationContext.getBean("myBean");

非常感谢任何帮助或指导。我在 Spring 上遇到的麻烦比我愿意承认的要多。

【问题讨论】:

    标签: java spring javabeans code-injection context.xml


    【解决方案1】:

    你可以使用spring的@Value注解,像这样:

    @Component
    public MyClass {
    
      @Value("${some.prop.name1}")
      private String myProp1;
    
    }
    

    file1.properties:

    some.prop.name1=value1
    

    我希望它会有所帮助。祝你好运。

    【讨论】:

      【解决方案2】:

      您是否可以这样做将取决于 bean 定义。它必须有一个 setLocations() 方法(或正确注释),S​​pring 将通过该方法注入值。

      如果存在,您将使用 bean 上的 getter 方法检索值。如果没有,您将需要修改 bean。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2016-12-17
        • 2016-06-13
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多