Properties 注入
- 通过 xml 配置
- 通过 @PropertySource 配置
- PropertyPlaceholderConfigurer
- PropertySourcesPlaceholderConfigurer
Properties 的使用
- 在 xml 配置文件中使用
- 通过 @Value 注入使用
- 通过 Environment 获取
- 通过 application.properties 获取
Spring Boot 相关
- @ConfigurationProperties
- 配置优先级
Properties 配置
通过 xml 配置
<context:property-placeholder location="classpath:sys.properties" />
通过 @PropertySource 配置
@PropertySource("classpath:sys.properties")
@Configuration
public class DemoConfig {
}
@PropertySource 在这里必须搭配 @Configuration 来使用。
PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:sys.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<!-- 这里可以配置一些属性 -->
</bean>
java configuration 版本
@Bean
public PropertyPlaceholderConfigurer propertiess() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")};
ppc.setLocations(resources);
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
PropertySourcesPlaceholderConfigurer
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:sys.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<!-- 这里可以配置一些属性 -->
</bean>
java configuration 版本
@Bean
public PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")};
pspc.setLocations(resources);
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
Properties 的使用
在 xml 配置文件中使用
<bean id="xxx" class="com.demo.Xxx">
<property name="url" value="${mysql.jdbc.url}" />
</bean>
通过 @Value 注入使用
@Value("${demo.jdbc.url}")
private String url;
通过 Environment 获取
只有使用注解 @PropertySource 的时候可以用,否则会得到 null。
@Autowired
private Environment env;
public String getUrl() {
return env.getProperty("demo.jdbc.url");
}
通过 application.properties 获取
demo.database.url=jdbc:mysql:
Spring Boot 相关
@ConfigurationProperties
application.properties
demo.db.url=jdbc:mysql:
demo.db.username=test
demo.db.password=123456
@Configuration
@ConfigurationProperties(prefix = "demo.db")
@Data
public class DataBase {
String url;
String username;
String password;
}
配置优先级
java -Dspring.profiles.active=env -jar app.jar
如果存在这两个文件,application.properties 和 application-env.properties ,则两个文件中的配置都会注册进去,如果有重复的 key,application-env.properties 文件中的优先级较高。总结:启动参数 > application-{env}.properties > application.properties