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內容為:
1
2
3
4
5
|
server.context-path=/product server.port=8080 author.name=Product author.age=25 |
application-dev.properties內容為:
1
2
3
4
5
|
server.context-path=/dev server.port=9090 author.name=Dev author.age=21 |
DemoApplication的代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@ 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前綴符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@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的內容:
1
|
spring.profiles.active=dev |
表示dev環境,運行Spring Boot APP…
可以看到配置信息就是dev的信息,可以切換成spring.profiles.active=prod測試看看。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://dtbuluo.com/125.html?utm_source=tuicool&utm_medium=referral