【问题标题】:How can I make properties in properties files mandatory in Spring?如何在 Spring 中强制属性文件中的属性?
【发布时间】:2011-02-15 09:59:50
【问题描述】:

我有一个包含以下节点的 ApplicationContext.xml 文件:

<context:property-placeholder 
location="classpath:hibernate.properties, classpath:pathConfiguration.properties" />

它指定我的应用程序将使用两个properties 文件。

pathConfiguration.properties里面,定义了一些路径,比如:

PATH_ERROR=/xxx/yyy/error
PATH_SUCCESS=/xxx/yyy/success

PathConfiguration bean 的每个路径都有设置器。

问题是:当其中一些强制路径未定义时,不会引发错误。我应该如何以及在哪里处理这个问题?

【问题讨论】:

  • 您在项目中使用的 Spring 版本是什么?您在下面的评论中引用了一个有点旧的版本。
  • 是的,我忘了提。春季 2.5

标签: java spring error-handling javabeans


【解决方案1】:

我不确定我是否完全理解您的问题,但可能有多种方法可以解决此问题。一种是通过使用构造函数注入来强制路径。然后,您可以在构造函数中验证传入的值,例如,如果为 null,则抛出 BeanInitializationException 实例。

【讨论】:

  • 我想你理解了这个问题 :-) 事实上我对 Spring 完全陌生,不知道如何实现构造函数注入。我将阅读一些有关它的内容,如果这是解决方案,我将回到这里为您 +1。 (如果你能用一个例子更新你的答案,那就太好了)
  • ... 认为我在这里找到了解决方案:static.springsource.org/spring/docs/2.0.3/reference/…(项目 3.5.1.2.1)。你是这个意思吗?
  • 是的,我就是这么想的。我没有我的例子。但需要注意的是,构造函数注入的好处是可以确保传入所需的参数。但请记住,这并不能保证它们是正确的。您可能仍想验证构造函数中的属性值,如果不正确则抛出 BeanInitializationException。
【解决方案2】:

通过&lt;context:property-placeholder ... /&gt; 配置的PropertyPlaceholder 的标准行为会在某个地方一旦需要它就无法解析属性时引发异常,只要您不另外配置它​​。

对于您的情况,如果您有一个 Bean 需要这样的一些属性,那么当无法解析该值时它将失败。比如这样:

public class PropertiesAwareBean {

  @Value("${PATH_ERROR}")
  private String errorPath;

  String getErrorPath() {
    return errorPath;
  }

}

如果您想放宽 PropertyPlaceholder 并且不让它在无法解析属性时引发异常,您可以配置 PropertyPlaceholder 以忽略无法解析的属性,例如 &lt;context:property-placeholder ignore-unresolvable="true" ... /&gt;

【讨论】:

    【解决方案3】:

    加强参数验证的一种方法是在 bean 文件中切换到经典的 PropertyPlaceholderConfigurer bean。

    PropertyPlaceholderConfigurer 具有可用于调整其行为的属性,并指定在缺少某些键时是否引发异常(查看 setIgnoreUnresolvablePlaceholderssetIgnoreResourceNotFound)。

    如果我没记错的话,在 Spring 2.5 中,&lt;context:property-placeholder&gt; 仅支持 location 属性(不过情况可能已经改变)。

    【讨论】:

    • 您对 Spring 2.5 是正确的,只有一个 location 和一个 properties-ref 属性。正如我在回答中提到的,Spring 3.0 在&lt;context:property-placeholder /&gt;-Tag 上提供了更多配置可能性。
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多