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

时间:2017-10-12 20:11:59

标签: java spring

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

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

3 个答案:

答案 0 :(得分:1)

与其他配置类(ApplicationConfiguration等)一起,我创建了一个带有注释@Service的类,这里我有以下字段来访问我文件中的属性:

@Service
public class Properties (){

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

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

}

然后我可以自动装配该类并从我的属性文件中获取属性

答案 1 :(得分:1)

答案是, 这取决于。

如果属性是配置值, 然后配置'21781','4243','15787' '21781','4249','15793' '21781','4255','15823' '21782','4243','15787' '21782','4249','15793' '21782','4255','15823' '21782','4285','15526' '21782','4288','17588' '21783','4243','15787' '21783','4249','15793' '21783','4255','15823' '21783','4285','15527' '21783','4288','17588' '21784','4243','15787' '21784','4249','15793' '21784','4255','15823' '21784','4285','15527' '21784','4288','15542' '21785','4243','15877' '21785','4249','15793' '21785','4255','15823' '21785','4285','15527' '21785','4288','17588' (下面是Spring xml配置文件的示例)。

propertyConfigurer

以这种方式配置时, 找到的最后一个文件的属性覆盖那些找到的earler (在位置列表中)。 这允许您发送war文件中捆绑的标准configuration.properties文件,并在每个安装位置存储configuration.overrides.properties以解决安装系统差异。

一旦你有了propertyConfigurer, 使用<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> 注释注释您的类。 这是一个例子:

@Value

不需要将配置值集群到一个类中, 但这样做可以更容易地找到值的使用位置。

答案 2 :(得分:0)

@Value将是一种简单易用的方法,因为它会将属性文件中的值注入您的字段。

  

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

getEnvironment

不同
  

使用 property-placeholder 不会将属性公开给   Spring Environment - 这意味着检索这样的值   不起作用 - 它将返回null

当您使用<context:property-placeholder location="classpath:foo.properties" />并使用env.getProperty(key);时,它将始终返回null。

使用getEnvironment查看此帖子中的问题:Expose <property-placeholder> properties to the Spring Environment

此外,在Spring Boot中,您可以使用 @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

相关问题