讀取Properties文件的幾種方式
讀取 Properties 文件
1.在xml 配置文件中使用"${}"
<bean id="xxx" class="com.javadoop.Xxx">
<property name="url" value="${javadoop.jdbc.url}" />
</bean>
2. 通過(guò)@Value注解注入
@Value("${javadoop.jdbc.url}")
private String url;
3.通過(guò)Environment獲取
注意:只有使用注解 @PropertySource 的時(shí)候才可以使用,否則會(huì) null ; 如果是 SpringBoot 的application.properties 注冊(cè) 的节槐,也可以
@Autowired
private Environment env;
public String getUrl() {
return env.getProperty("javadoop.jdbc.url");
}
Properties的使用
1.通過(guò)XML配置
<context:property-placeholder location="classpath:sys.properties" />
2.通過(guò)@PropertySource配置
@PropertySource("classpath:sys.properties")
@Configuration
public class JavaDoopConfig {
}
3.PropertyPlaceholderConfigurer(Spring3.1之前)
@Bean
public PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")};
pspc.setLocations(resources);
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
Spring Boot
我們先去生成一個(gè) SpringBoot 項(xiàng)目搀庶,不會(huì)的可以使用 SpringBoot
的 在線生成服務(wù),直接下載到本地即可拐纱。
在生成的項(xiàng)目中,默認(rèn)包含一個(gè) application.properties 的配置文件哥倔,只需配置秸架,SpringBoot 會(huì)幫我們注冊(cè)。
如果需要換配置文件咆蒿,則在啟動(dòng)時(shí)指定即可:
java -Dspring.config.location=classpath:sys.properties -jar app.jar
application-{env}.properties
在 application.properties 的基礎(chǔ)上东抹,我們還需要新建 application-dev.properties 和application-prd.properties,用于配置環(huán)境相關(guān)的信息沃测,然后啟動(dòng)的時(shí)候指定環(huán)境:
java -Dspring.profiles.active=prd -jar app.jar
如果 application.properties 和 application-prd.properties 有key沖突缭黔,application-prd.properties 的優(yōu)先級(jí)較高。
@ConfigurationProperties
這個(gè)注解是 SpringBoot 才有的,我們?cè)?application.properties
中加入
javadoop.database.url=jdbc:mysql:
javadoop.database.username=admin
javadoop.database.password=admin123456
java文件
@Configuration
@ConfigurationProperties(prefix = "javadoop.database")
public class DataBase {
String url;
String username;
String password;
// getters and setters
}
這樣蒂破,就在 Spring 的容器中自動(dòng)注冊(cè)了一個(gè)類型為 DataBase 的 bean 了馏谨,而且屬性都已經(jīng) set 好了
屬性配置的覆蓋順序:
啟動(dòng)參數(shù) > application-{env}.properties > application.properties
使用啟動(dòng)參數(shù)動(dòng)態(tài)設(shè)置屬性:
java -Djavadoop.database.password=admin4321 -jar app.jar