SpringBoot會默認加載application.yml和application.properties文件,可是有時候咱們會對一些配置進行分類管理,如把數據庫等配置進行單獨配置,那這時候要怎麼辦呢,SpringBoot做爲如今最流行的項目怎麼會沒有想到這點呢,接下來將演示如何讀取自定義配置文件。html
首先在resource/config文件夾下新建一個datasource.properties文件來進行數據庫相關的配置以下:java
#數據庫地址 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/wusy?characterEncoding=UTF-8&useSSL=false #數據庫用戶名 spring.datasource.username=root #數據密碼 spring.datasource.password=123456 #數據庫驅動 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #最大鏈接數 spring.datasource.tomcat.max-active=20 #最大空閒數 spring.datasource.tomcat.max-idle=8 #最小空閒數 spring.datasource.tomcat.min-idle=8 #初始化鏈接數 spring.datasource.tomcat.initial-size=10 #對池中空閒的鏈接是否進行驗證,驗證失敗則回收此鏈接 spring.datasource.tomcat.test-while-idle=true
在啓動類中添加讀取datasource.properties文件的註解@PropertySourcemysql
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; /** * @author wusy * Company: xxxxxx科技有限公司 * Createtime : 2020/2/24 21:42 * Description : SpringBoot應用啓動器 */ @SpringBootApplication @PropertySource(value = {"classpath:config/datasource.properties"}, encoding = "utf-8") public class Application { private static Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication application = new SpringApplication(Application.class); application.run(args); logger.info("啓動成功"); } }
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author wusy * Company: xxxxxx科技有限公司 * Createtime : 2020/2/24 21:54 * Description : */ @RestController @RequestMapping("/api/demo") public class HelloWorldController { @Value("${spring.datasource.url}") private String url; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "hello world," + url; } }
運行應用,打開瀏覽器,在地址欄輸入http://127.0.0.1:8787/api/demo/hello,觀察結果web
這裏只作的簡單的演示,推薦一個寫的更詳細的博客https://www.cnblogs.com/huanzi-qch/p/11122107.html,有興趣的能夠看看。spring