配置文件
- 为了让 Spring Boot 更好的生成配置元数据文件,我们需要添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
配置项:
自定义属性配置
application.properties内容如下:
my1.age=22
my1.name=battcn
MyProperties1.java内容如下:
@Component
@ConfigurationProperties(prefix = "my1")
public class MyProperties1 {
private int age;
private String name;
// getter setter
}
使用方式:Spring4.x 以后,推荐使用构造函数的形式注入属性
@RequestMapping("/map")
@RestController
public class PropertiesController {
private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);
private final MyProperties1 myProperties1;
@Autowired
public PropertiesController(MyProperties1 myProperties1) {
this.myProperties1 = myProperties1;
}
@GetMapping("/age")
public MyProperties1 myProperties1() {
log.info(myProperties1.getAge());
return myProperties1.getAge();
}
}
自定义文件配置
定义一个名为 my2.properties 的资源文件,内容如下:
my2.age=22
my2.name=Levin
MyProperties2.java 文件内容如下
@Component
@PropertySource("classpath:my2.properties")
@ConfigurationProperties(prefix = "my2")
public class MyProperties2 {
private int age;
private String name;
// getter setter
}
多环境化配置(开发、测试、生产)
- application-dev.properties(开发环境配置文件)
server.servlet.context-path=/dev
server.port=8081
- application-test.properties(测试环境配置文件)
server.servlet.context-path=/test
server.port=8082
- application-prod.properties(生产环境测试文件)
server.servlet.context-path=/prod
server.port=8080
在
application.properties
配置文件中写入spring.profiles.active=dev
访问路径为(http://localhost:8081/dev)
对应开发环境。
命令行动态选择运行环境
java -jar xxx.jar --spring.profiles.active=dev