簡體   English   中英

在Spring中從屬性文件獲取值的最佳方法是什么?

[英]What is the Best way to get the values from the Properties File in 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; }

}

然后,我可以自動連接類並從屬性文件中獲取屬性

答案是,這取決於。

如果屬性是配置值,則配置一個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;

不需要將配置值聚集到一個類中,但是這樣做可以更輕松地找到使用這些值的位置。

@Value將是簡單易用的方式,因為它將值從屬性文件注入到您的字段中。

在Spring 3.1中添加的較舊的PropertyPlaceholderConfigurer和新的PropertySourcesPlaceholderConfigurer都可以在bean定義屬性值和@Value批注中解析$ {…}占位符。

getEnvironment不同

使用property-placeholder不會將屬性公開給Spring Environment-這意味着檢索這樣的值將不起作用-它將返回null

當您使用<context:property-placeholder location="classpath:foo.properties" />並使用env.getProperty(key); 它將始終返回null。

有關使用getEnvironment的問題,請參見此文章: 將<property-placeholder>屬性公開到Spring環境

此外,在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

引用自: 春季物業

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM