【问题标题】:Spring 3.1 basic usage of Envirionment and PropertySourceSpring 3.1 Environment和PropertySource的基本用法
【发布时间】:2013-08-12 19:33:38
【问题描述】:

我想在启动时将属性值注入 Spring 上下文。 我正在尝试使用 Spring 3.1 的新 Environment 和 PropertySource 功能来做到这一点。

在加载Spring上下文的类中,我定义自己的PropertySource类如下:

private static class CustomPropertySource extends PropertySource<String> {
   public CustomPropertySource() {super("custom");}
      @Override
      public String getProperty(String name) {
      if (name.equals("region")) {
         return "LONDON";
      }
      return null;
}

然后,我将此属性源添加到应用程序上下文中:

ClassPathXmlApplicationContext springIntegrationContext = 
   new ClassPathXmlApplicationContext("classpath:META-INF/spring/ds-spring-intg-context.xml");
context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
context.refresh();
context.start();

在我的一个 bean 中,我尝试访问属性值:

@Value("${region}")
public void setRegion(String v){
   ...
}

bur 收到以下错误:

java.lang.IllegalArgumentException: 原因: java.lang.IllegalArgumentException:无法解析占位符 字符串值中的“区域”[${region}]

非常感谢任何帮助

【问题讨论】:

    标签: spring spring-environment


    【解决方案1】:

    当您将 XML 文件位置作为构造函数参数传递给 ClassPathXmlApplicationContext(..) 时,它会立即执行 context.refresh()/context.start() 方法。因此,通过传入您的 XML 位置,您实际上是一次性完成所有操作,并且在您调用 context.getEnvironment().getPropertySources... 时上下文已经启动/加载。

    试试这个;

    ClassPathXmlApplicationContext springIntegrationContext = 
       new ClassPathXmlApplicationContext();
    context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
    context.setLocations("classpath:META-INF/spring/ds-spring-intg-context.xml");
    context.refresh();
    

    它将设置您的来源,然后是您的 xml,然后启动应用上下文。

    【讨论】:

      猜你喜欢
      • 2012-11-24
      • 2012-12-22
      • 1970-01-01
      • 2014-02-11
      • 2012-10-05
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多