spring
配置
PropertyPlaceholderConfigurer
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="fileEncoding" value="utf-8"/>
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:${env}/important.properties</value>
<value>classpath:${env}/sys.properties</value>
</list>
</property>
</bean>
也可以如下兩種形式:
Context
<!-- spring命名空間 -->
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
<context:property-placeholder location="classpath:packagename/*.properties" />
util
<!-- spring命名空間 -->
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
<util:properties id="config" location="classpath:packagename/config.properties"/>
<!-- 使用如下:例 mysql.driverClassName -->
<bean id="client" class="com.package.businessname.service.impl.XXXServiceImpl">
<constructor-arg index="0" value="#{config['properties.keyName']}"/>
</bean>
使用
- 在 xml 配置文件中使用
即自動替換 ${} 裏面的值。
<property name="username" value="${pip.jdbc.username}" />
- 通過 @Value 注入使用
@Value("${pip.jdbc.username}")
private String username;
- -
Properties prop = new Properties();
InputStream inStream = ConfigLoader.class.getClassLoader().getResourceAsStream("common.properties");
prop.load(inStream);
username= Long.parseLong(prop.getProperty("pip.jdbc.username"));
spring boot
每個項目都默認有一個 application.properties 文件,這個配置文件不需要像前面說的那樣進行註冊,Spring Boot 會幫我們自動註冊。
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=1qaz2wsx
爲了給不同的環境指定不同的配置,我們可以作如下配置
application-{env}.properties
啓動時,則執行如下
java -Dspring.profiles.active={env} -jar app.jar
java文件,如下:
@Configuration
//自動在 Spring 的容器註冊一個類型爲 DataSource 的 javabean ,且屬性都已經 set 過
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSource {
String url;
String username;
String password;
// getters and setters
}