Some configuration parameters during development and after going online are not available, such as database connection, SMS verification, etc
springboot provides us with a way to differentiate environment configuration
Different environment configurations for the same profile
Three bars can be used in the same configuration file application.yml to distinguish the environment
server: port: 8080 spring: profiles: active: dev #Default boot environment # Development environment configuration --- spring: profiles: dev myconf: user: name: Development-Ha-ha # Production environment configuration --- spring: profiles: prod myconf: user: name: production-Hey hey hey
Startup class:
@SpringBootApplication @RestController public class ProfileApp { @Value("${myconf.user.name}") private String userName; public static void main(String[] args) { SpringApplication.run(ProfileApp.class, args); } @GetMapping("/name") public String getUserName(){ return userName; } }
After starting the project, view the log:
2018-11-23 16:59:53.131 INFO 90732 --- [ restartedMain] com.yimingkeji.profile.ProfileApp : The following profiles are active: dev #The current profile is dev
Visit http://localhost:8080/name
Development - ha ha
If the boot environment is modified to prod
spring: profiles: active: prod
Visit again after startup http://localhost:8080/name
Production - hehe hehe
Different profiles, different environments
You can also add configuration files, named after the application environment, such as
application.yml #Default configuration application-dev.yml # Development environment configuration application-prod.yml # Production environment configuration
application.yml
server: port: 8080 spring: profiles: active: dev #Default boot environment
application-dev.yml
myconf: user: address: Xihu District, Hangzhou City
application-prod.yml
myconf: user: address: Beijing, Beijing
Interface:
@Value("${myconf.user.address}") private String address; @GetMapping("/address") public String getAddress(){ return address; }
First set the boot environment to dev, and then access http://localhost:8080/address
Xihu District, Hangzhou City
Set environment to prod
Beijing, Beijing
Of course, these two methods can be used together. Keep the previous configuration in application.yml:
# Development environment configuration --- spring: profiles: dev myconf: user: name: Development-Ha-ha # Production environment configuration --- spring: profiles: prod myconf: user: name: production-Hey hey hey
Modify interface:
@Value("${myconf.user.name}") private String userName; @Value("${myconf.user.address}") private String address; @GetMapping("/user") public String user(){ return "Full name:" + userName + ", Address:" + address; }
Environment dev, accessing http://localhost:8080/user
Name: development haha, address: Xihu District, Hangzhou