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十分鐘