什么是从Spring中的属性文件中获取值的最佳方法?

问题描述:

我已经使用以下方法从属性中获取值。但我想知道哪一个是最适合遵循编码标准的?另外,还有其他方法可以从Spring的属性文件中获取值吗?什么是从Spring中的属性文件中获取值的最佳方法?

PropertySourcesPlaceholderConfigurer 
getEnvironment() from the Spring's Application Context 
Spring EL @Value 

随着其他配置类(ApplicationConfiguration等),创建一个类注释@Service在这里,我有以下字段在我的文件访问属性:

@Service 
public class Properties(){ 

    @Value("${com.something.user.property}") 
    private String property; 

    public String getProperty(){ return this.property; } 

} 

然后我可以autowire这个类,并从我的属性文件中获取属性

@Value将是简单易用的使用方式,因为它会将属性文件中的值注入到字段中。

Spring 3.1中新增的PropertyPlaceholderConfigurer和新的PropertySourcesPlaceholderConfigurer在bean定义属性值和@Value注释中解析了$ {...}占位符。

不像getEnvironment

使用财产占位不会暴露性质的 Spring环境中 - 这意味着检索这样 的价值将无法正常工作 - 它会返回null

当您使用<context:property-placeholder location="classpath:foo.properties" />并且您使用env.getProperty(key);它会一直返回null。

看到这个帖子使用getEnvironment问题:Expose <property-placeholder> properties to the Spring Environment

此外,在春季启动时,您可以使用@ConfigurationProperties与定义自己的属性层次和类型安全的application.properties。而且您不需要为每个字段都放置@Value。

@ConfigurationProperties(prefix = "database") 
public class Database { 
    String url; 
    String username; 
    String password; 

    // standard getters and setters 
} 

在application.properties:

database.url=jdbc:postgresql:/localhost:5432/instance 
database.username=foo 
database.password=bar 

引用自:properties with spring

答案是, 它依赖。

如果属性是配置值,则 然后配置propertyConfigurer (以下是Spring xml配置文件的示例)。

<bean id="propertyConfigurer" 
     class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> 
    <property name="ignoreResourceNotFound" value="true" /> 
    <property name="locations"> 
     <list> 
      <value>classpath:configuration.properties</value> 
      <value>classpath:configuration.overrides.properties</value> 
     </list> 
    </property> 
</bean> 

当这种方式配置, 从最后一个文件的属性找到替代那些被发现早期的版本 (在地点列表)。 这允许您发布捆绑在war文件中的标准configuration.properties文件,并在每个安装位置存储configuration.overrides.properties以说明安装系统差异。

一旦你有一个propertyConfigurer, 使用@Value注释来注释你的类。 下面是一个例子:

@Value("${some.configuration.value}") 
private String someConfigurationValue; 

它不需要群集配置值为一类, 但这样做使得它更容易找到其中使用的值。

+0

哦哇 - XML配置。多么有趣的古董...... –