Spring Boot提供了3种方式读取application.properties配置文件。分别为Environment类、@Value和@ConfigurationProperties。
Environment
Environment是一个通用的读取应用程序运行时的环境变量的类,可通过key-value方式读取application.properties。
例:
- application.properties添加
test.msg=read config
- 在测试类中使用@Autowired注入Enviroment类的对象
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { SpringbootDemoApplication.class,
PropertySourcesPlaceholderConfigurer.class }, initializers = { ConfigFileApplicationContextInitializer.class })
public class EnvReaderConfigTest {
@Autowired
private Environment env;
@Autowired
private StudentProperties spro;
@Test
public void test1() {
System.out.println(env.getProperty("test.msg"));
}
}
@Value
例:
@Value("${test.msg}")
private String msg;
@Test
public void test1() {
System.out.println(msg);
}
${key}获取application.properties对应的key的value
@ConfigurationProperties
使用@ConfigurationProperties先要建立配置文件和对象的映射关系,然后使用@Autowired注入对象。
例:
- 全局配置文件中添加:
stu.name=zhangsan
stu.age=18
- 建立对象与其映射
@ConfigurationProperties(prefix = "stu")//配置文件的key的前缀
@Component//声明一个组件,被控制器依赖注入
@Data
public class StudentProperties {
private String name;
private int age;
}
- 注入StudentProperties对象即可使用。
@Autowired
private StudentProperties spro;
@Test
public void test1() {
System.out.println(spro.toString());
}
ps:没有get、set方法,或者命名不规范有可能会获取不到值。
@PropertySource
上面几个默认都是获取全局配置文件,可使用@PropertySource
找到配置文件,然后利用上面3种任意一个即可。
举例@PropertySource+@Value
读取其他配置文件
- 创建
test.properties
,添加test.msg=hello world
- 创建类获取值
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { SpringbootDemoApplication.class,
PropertySourcesPlaceholderConfigurer.class }, initializers = { ConfigFileApplicationContextInitializer.class })
@PropertySource({ "test.properties"})
public class PropertySourceTest {
@Value("${test.msg}")
private String msg;
@Test
public void test1() {
System.out.println(msg);
}
}