属性加载顺序
配置属性加载的顺序
- 开发者工具 `Devtools` 全局配置参数;
- 单元测试上的 `@TestPropertySource` 注解指定的参数;
- 单元测试上的 `@SpringBootTest` 注解指定的参数;
- 命令行指定的参数,如 `java -jar springboot.jar --name="demo"`;
- 命令行中的 `SPRING_APPLICATION_JSONJSON` 指定参数, 如 `java -Dspring.application.json='{"name":"demo"}' -jar springboot.jar`
- `ServletConfig` 初始化参数;
- `ServletContext` 初始化参数;
- JNDI参数(如 `java:comp/env/spring.application.json`);
- Java系统参数(`System.getProperties()`);
- 操作系统环境变量参数;
- `RandomValuePropertySource` 随机数,仅匹配:`ramdom.*`;
- JAR包外面的配置文件参数(`application-{profile}.properties(YAML)`)
- JAR包里面的配置文件参数(`application-{profile}.properties(YAML)`)
- JAR包外面的配置文件参数(`application.properties(YAML)`)
- JAR包里面的配置文件参数(`application.properties(YAML)`)
- `@Configuration`配置文件上 `@PropertySource` 注解加载的参数
- 默认参数(通过 `SpringApplication.setDefaultProperties` 指定)
数字小的优先级越高,即数字小的会覆盖数字大的参数值。
属性配置方式
- PropertyPlaceholderConfigurer:
-
- <context:property-placeholder location="classpath:sys.properties" />
- @Bean的方式
@Bean public PropertyPlaceholderConfigurer propertiess() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")}; ppc.setLocations(resources); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; }
- xml 的方式
<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>
- 通过 springboot 扩展方式:
@Bean public CommandLineRunner commandLineRunner() { return (args) -> { System.setProperty("name", "demo"); }; }
-
通过 @PropertySource 配置
@PropertySource("classpath:sys.properties") @Configuration public class DemoConfig { }
- @SpringBootTest(value = { "name=javastack-test", "sex=1" })
属性获取方式
- 占位符:${PlaceHolder}
- SpEL 表达式 #{}
- 通过 Environment 获取
// 只有使用注解 @PropertySource 的时候可以用,否则会得到 null。 @Autowired private Environment env; public String getUrl() { return env.getProperty("demo.jdbc.url"); }
- 通过 @Value 注入
@Value("${demo.jdbc.url}") private String url;
- @ConfigurationProperties
@Configuration @ConfigurationProperties(prefix = "demo.db") @Data public class DataBase { String url; String username; String password; }