SpringBoot
极大的简化了配置,经常使用配置均可以application.yml
或者application.properties
文件中设置。java
介绍项目的同时,推荐相关IntelliJ IDEA
快捷键,熟能生巧,无需死记硬背。git
SpringBoot
经常使用配置介绍SpringBoot
经常使用配置介绍点击resources -> New -> File,或者快捷键
ALT+Insert
,命名application.yml
或者application.properties
,推荐使用application.yml
更加简洁github
server:port:
设置服务端口,server:servlet:context-path:
设置服务根路径spring
# 服务相关配置 server: # 服务端口配置 port: 8080 # 服务根路径配置 servlet: context-path: /dev
启动服务,快捷键
Shift+F10
windows
debug:
开启debug
模式,开启后能够看到服务启动详细过程,SpringBoot
加载了哪些配置和class
,适合新手了解SpringBoot
内部机制app
# 开启debug模式 debug: true
通常开发过程会分多套环境,简单来讲,开发环境一套配置,生产环境一套配置,不一样环境配置不一样,如何处理?ide
点击resources -> New -> File,新建配置文件
application-dev.yml
spring-boot
# 服务相关配置 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
生产环境配置,请本身动手体验,看看是否生效,切记:无它,熟能生巧
SpringBoot
解析配置生成元数据,建议添加依赖
<!--该依赖只会在编译时调用--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
点击
resources -> New -> File
,新建配置文件user.properties
,写下以下内容
company.user.name=Mkeeper company.user.age=28
新建
UserProperties.java
用来保存user.properties
中的内容,方便经过对象访问
@Configuration //指定配置文件,若是不指定,默认解析“application.yml” @PropertySource("classpath:user.properties") //前缀 @ConfigurationProperties(prefix = "company.user") public class UserProperties { private String name; private Integer age; // 省略 get set @Override public String toString() { return "UserProperties {" + "name='" + name + '\'' + ", age=" + age + '}'; } }
若是删除@PropertySource("classpath:user.properties")
,SpringBoot
将默认解析application.yml
中的配置
新建
UserController.java
,注入UserProperties
@RestController public class UserController { private static final Logger log = LoggerFactory.getLogger(UserController.class); @Autowired private UserProperties userProperties; @GetMapping("/user") public String user() { log.info("info:"); return userProperties.toString(); } }
快捷键Ctrl+E
能够快速查看最近阅读过的文件
测试
无他,熟能生巧,与你们共勉,有任何建议,欢迎留言探讨,本文源码。
欢迎关注博主公众号:Java十分钟