【问题标题】:how to inject into a bean the values of a properties file read from controller?如何将从控制器读取的属性文件的值注入到 bean 中?
【发布时间】:2012-11-20 12:43:40
【问题描述】:

我想使用控制器从 .properties 文件中读取属性,并将其值显示在 jsp 文件中,这是一个使用依赖注入的视图,方法是将检索到的属性存储在 pojo 中。

【问题讨论】:

  • 请尝试提交一些内容,以便帮助挖掘您的问题
  • 为什么要将值存储在 POJO 中,我认为这与 MessageSource org.springframework.context.support.ReloadableResourceBundleMessageSource 有关 - 以下是谷歌建议的第一个链接:viralpatel.net/blogs/…

标签: java spring properties dependency-injection


【解决方案1】:

为此使用PropertyPlaceholderConfigurer。属性将由 spring 加载,因此您的控制器无需执行此操作。您可以将属性直接注入到您的视图中。

【讨论】:

  • 嗨,这可能是个愚蠢的问题,但我不知道答案。如果 spring 通过 PropertyPlaceholder 加载属性文件,我如何在我的 jsp(view) 中访问它
【解决方案2】:

试试这个

@Component
class MyComponent {

  @Property(key = "proo.xmlurl")
  public void setUrlString(String urlStr) {
        try {
            this.url = new URL(urlStr);
        } catch(MalformedURLException e) {
            throw new IllegalArgumentException(urlStr + " is not a valid http         url", e);
        }
    }
}

在你的属性文件中放这个

proo.xmlurl=${proo.xmlurl}

【讨论】:

    【解决方案3】:

    AppContext 可以有这个:

    <context:property-placeholder location="classpath:my.properties" ignore-unresolvable="true"/>
    

    控制器可以有这个

    @Value("${language}")
    private String language;
    
    @Value("${allLanguages}")
    private String allLanguages;
    

    properties 文件包含此或类似内容的位置

    language = java 
    alllanguages = java and \
                   c++
    somethingelse = whatever
    

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 2012-03-04
      • 1970-01-01
      • 2019-03-03
      相关资源
      最近更新 更多