日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Springboot-读取核心配置文件及自定义配置文件

發布時間:2025/4/9 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Springboot-读取核心配置文件及自定义配置文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

讀取核心配置文件

核心配置文件是指在resources根目錄下的application.properties或application.yml配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。

核心配置文件application.properties內容如下:

server.port=9090 test.msg=Hello World Springboot!?
  • 使用@Value方式(常用)

@RestControllerpublic class WebController {@Value("${test.msg}")private String msg;@RequestMapping(value = "index", method = RequestMethod.GET)public String index() {return "The Way 1 : " +msg;}}

?

注意:在@Value的${}中包含的是核心配置文件中的鍵名。在Controller類上加@RestController表示將此類中的所有視圖都以JSON方式顯示,類似于在視圖方法上加@ResponseBody。

訪問:http://localhost:9090/index?時將得到The Way 1 : Hello World Springboot!

  • 使用Environment方式

@RestController public class WebController {@Autowiredprivate Environment env;@RequestMapping(value = "index2", method = RequestMethod.GET)public String index2() {return "The Way 2 : " + env.getProperty("test.msg");} }? 注意:這種方式是依賴注入Evnironment來完成,在創建的成員變量private Environment env上加上@Autowired注解即可完成依賴注入,然后使用env.getProperty("鍵名")即可讀取出對應的值。

訪問:http://localhost:9090/index2?時將得到The Way 2 : Hello World Springboot!


讀取自定義配置文件

  • 通過@ConfigurationProperties注解,通過getter、setter方法注入及獲取配置

為了不破壞核心文件的原生態,但又需要有自定義的配置信息存在,一般情況下會選擇自定義配置文件來放這些自定義信息,這里在resources/config目錄下創建配置文件my-web.properties

resources/config/my-web.properties內容如下:

web.name=isea533
web.jdbc.username=root
web.jdbc.password=root?

創建管理配置的實體類:

@ConfigurationProperties(locations = "classpath:config/my-web.properties", prefix = "web") @Component public class MyWebConfig{private String name;private Jdbc jdbc;class Jdbc {private String username;private String password;//getter... }public Integer gePort(){return this.port;}public Jdbc getJdbc() {return this.jdbc;} } 注意:
  • 在@ConfigurationProperties注釋中有兩個屬性:

    • locations:指定配置文件的所在位置
    • prefix:指定配置文件中鍵名稱的前綴(我這里配置文件中所有鍵名都是以web.開頭)
  • 使用@Component是讓該類能夠在其他地方被依賴使用,即使用@Autowired注釋來創建實例。

    • 通過@PropertySource注解,然后使用@Value逐個注入配置

    1 @Configuration 2 @PropertySource("classpath:test.properties") 3 public class ELConfig { 4 5 @Value("${book.name}") 6 private String bookName; 7 8 //PropertySourcesPlaceholderConfigurer這個bean,這個bean主要用于解決@value中使用的${…}占位符。假如你不使用${…}占位符的話,可以不使用這個bean。 9 @Bean 10 public static PropertySourcesPlaceholderConfigurer propertyConfigure() { 11 return new PropertySourcesPlaceholderConfigurer(); 12 } 13 14 public void outputSource() { 15 System.out.println(bookName); 16 } 17 }

    ?

    ?

    轉載于:https://www.cnblogs.com/junzi2099/p/7509045.html

    總結

    以上是生活随笔為你收集整理的Springboot-读取核心配置文件及自定义配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。