我已經使用以下方法從屬性中獲取值。但我想知道哪一個是最適合遵循編碼標準的?另外,還有其他方法可以從Spring的屬性文件中獲取值嗎?什麼是從Spring中的屬性文件中獲取值的最佳方法?
PropertySourcesPlaceholderConfigurer
getEnvironment() from the Spring's Application Context
Spring EL @Value
我已經使用以下方法從屬性中獲取值。但我想知道哪一個是最適合遵循編碼標準的?另外,還有其他方法可以從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
答案是, 它依賴。
如果屬性是配置值,則 然後配置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;
它不需要羣集配置值爲一類, 但這樣做使得它更容易找到其中使用的值。
哦哇 - XML配置。多麼有趣的古董...... –