自定义属性与加载
在使用SpringBoot的时候,我们经常需要自定义一些属性,接下来我要介绍两个比较常用且简单的定义方式:
以下配置写入application.properties中
pro1.name=hjw
pro1.age=22
pro2.name=pwt
pro2.age=18
方法1:通过@Component @ConfigurationProperties(prefix = "pro1")组合注解的方式
@Data
@Component
@ConfigurationProperties(prefix = "pro1")
public class Properties1 {
private String name;
private int age;
}
方法2:通过@Value("${参数}")注解来加载对应的配置属性
@Data
@Component
public class Properties2 {
@Value("${pro2.name}")
private String name;
@Value("${pro2.age}")
private int age;
}
通过单元测试来验证属性是否已经根据配置文件加载了
@SpringBootTest
class DemoApplicationTests {
@Autowired
private Properties1 properties1;
@Autowired
private Properties2 properties2;
@Test
void contextLoads() {
System.out.println(properties1.toString());
System.out.println(properties2.toString());
}
}
输出结果:
Properties1(name=hjw, age=22)
Properties2(name=pwt, age=18)
多环境配置
我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件。
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,如图:
于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
# 多环境配置文件激活属性
spring.profiles.active=prod