1.概述
SpringBoot
极大的简化了配置,常用配置都可以application.yml
或者application.properties
文件中设置。
2.SpringBoot
常用配置介绍
点击resources -> New -> File,或者快捷键ALT+Insert,命名application.yml或者application.properties,推荐使用application.yml更加简洁
server:port:设置服务端口,server:servlet:context-path:设置服务根路径
# 服务相关配置
server:
# 服务端口配置
port: 8080
# 服务根路径配置
servlet:
context-path: /dev
启动服务,快捷键Shift+F10
debug:开启debug模式,开启后可以看到服务启动详细过程,SpringBoot加载了哪些配置和class,适合新手了解SpringBoot内部机制
# 开启debug模式
debug: true
4. 多环境如何配置
一般开发过程会分多套环境,简单来说,开发环境一套配置,生产环境一套配置,不同环境配置不同,如何处理?
点击resources -> New -> File,新建配置文件application-dev.yml
# 服务相关配置
server:
# 服务端口配置
port: 8888
# 服务根路径配置
servlet:
context-path: /dev
# 开启debug模式
debug: true
点击resources -> New -> File,新建配置文件application-pro.yml
# 服务相关配置
server:
# 服务端口配置
port: 8080
# 服务根路径配置
servlet:
context-path: /
# 开启debug模式
debug: false
修改application.yml,配置激活配置
## 多环境配置,激活哪套配置
spring:
profiles:
active: dev
启动服务,快捷键Shift+F10
测试
spring:profiles:active: pro 生产环境配置,请自己动手体验,看看是否生效,切记:无它,熟能生巧
如何解析自定义配置文件
application-pro.yml添加connection
建立Auth类
@Configuration//可以用Component
//前缀
@ConfigurationProperties(prefix = "connection")
public class Auth {
private String username;
private String password;
private String remoteAddress;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
@Override
public String toString() {
return "Auth{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", remoteAddress='" + remoteAddress + '\'' +
'}';
}
}
测试类AuthController
@RequestMapping("/auth")
@RestController
public class AuthController {
@Autowired
Auth auth;
@GetMapping("/say")
public String say(){
return auth.toString();
}
}
测试:
工程目录
当application.peroperties中设置自定义属性时,假如属性和application-pro.yml中的一样会读取application-pro.yml的属性,
当application-pro.yml没有同样的属性时会读取application.peroperties的属性