Spring Boot的Profile配置详解

2023-05-21,,

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测试看看。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

《Spring Boot的Profile配置详解.doc》

下载本文的Word格式文档,以方便收藏与打印。