本篇文章主要介绍了 Spring Boot 的 Profile 配置详解, 小编觉得挺不错的, 现在分享给大家, 也给大家做个参考一起跟随小编过来看看吧
Profile 是 Spring Boot 用来针对不同的环境对不同的配置提供的支持, 全局 Profile 配置使用 application-{profile}.properties, 如: application-dev.properties 可以表示为开发环境
然后通过 application.properties 文件中的 spring.profiles.active=dev 来设置
在 src/main/resources 下面新建 application-dev.properties 和 application-prod.properties, 并配置相关内容信息
application-prod.properties 内容为:
- server.context-path=/product
- server.port=8080
- author.name=Product
- author.age=25
application-dev.properties 内容为:
- server.context-path=/dev
- server.port=9090
- author.name=Dev
- author.age=21
DemoApplication 的代码如下:
- @ SpringBootApplication(scanBasePackages = "com.example")
- @RestController
- public class DemoApplication {
- @Autowired
- private Author author;
- @RequestMapping("/")
- public String index() {
- return "Hello" + author.getName() + ",Your age is" + author.getAge();
- }
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- }
其中 Author 代码如下: @ConfigurationProperties 用作加载配置资源, prefix 前缀符
- @Component
- @ConfigurationProperties(prefix = "author")
- public class Author {
- private String name;
- private Long age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Long getAge() {
- return age;
- }
- public void setAge(Long age) {
- this.age = age;
- }
- }
设置 application.properties 的内容:
spring.profiles.active=dev
表示 dev 环境, 运行 Spring Boot APP
可以看到配置信息就是 dev 的信息, 可以切换成 spring.profiles.active=prod 测试看看
来源: http://www.phperz.com/article/18/0322/357138.html