springboot中獲取配置文件中屬性值的幾種方式小結(jié)
第一章、使用@Value注解
①@Value注解用于獲取配置文件中的屬性定義并綁定到Java Bean或?qū)傩灾?。在核心配置文件applicatin.properties中,添加兩個(gè)自定義配置項(xiàng)school.name和school.website。
②在SpringBootController中定義屬性,并使用@Value注解或者自定義配置值,并對(duì)其方法進(jìn)行測(cè)試
package com.example.springboot.web; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class SpringBootController { @Value("${school.name}") private String schoolName; @Value("${school.websit}") private String schoolWebsit; @RequestMapping(value = "/springBoot/first") @ResponseBody public String say() { return schoolName + "------" + schoolWebsit; } }
③訪問瀏覽器成功,說明成功通過@value讀取配置的屬性值
第二章、使用@PropertySource注解
2.1)指定文件路徑,在setter方法上添加@Value注解
@PropertySource(“classpath:coremail.properties”)是指定配置文件位置的注解。Spring 可以在類路徑下找到并加載這個(gè)coremail.properties屬性文件。需要再在屬性上面搭配@value注解使用其中定義的屬性值。
2.2)指定文件路徑,在屬性上添加@Value注解
2.3)使用ApplicationContextAware接口來獲得TConfig中對(duì)應(yīng)properties文件的屬性值
2.3.1)TaskConfig類與TestTaskConfig類
有兩個(gè)配置文件,使用兩個(gè)config類指定properties類文件路徑
@Configuration//當(dāng)一個(gè)類被標(biāo)注了@Configuration注解時(shí),Spring會(huì)將這個(gè)類識(shí)別為配置類, // 用于定義Bean的創(chuàng)建和配置。即使沒有顯式地定義Bean,配置類本身也可以被注入到其他類中 @PropertySource(value = {"classpath:mailSendConfig.properties"},encoding="utf-8") public class TaskConfig { }
@Configuration @PropertySource(value = {"classpath:testConfig.properties"},encoding="utf-8") public class TestTaskConfig { }
2.3.2)ConfigLoder類
用來加載config類
@Component public class ConfigLoder { @Autowired static TaskConfig taskConfig; @Autowired static TestTaskConfig testTaskConfig; public static TaskConfig getTaskConfig(){ return taskConfig; } public static TestTaskConfig getTestTaskConfig(){ return testTaskConfig; } }
2.3.3)啟動(dòng)類:啟動(dòng)只運(yùn)行一次
//@SpringBootApplication public class LineApplication implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception{ System.out.println("===================="); XXXXService mailSend =new XXXXService(); mailSend.run(); } public static void main(String[] args){ SpringApplication.run(LineApplication.class,args); } }
2.3.4)springUtil類實(shí)現(xiàn)ApplicationContextAware接口
通過實(shí)現(xiàn)ApplicationContextAware接口獲取ApplicationContext對(duì)象,來獲得TaskConfig中對(duì)應(yīng)properties文件的屬性值。
@Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } public static String getProperty(String propertyName) { return getApplicationContext().getEnvironment().getProperty(propertyName); } public static String getProperty(Class clazz, String PropertyName) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(clazz); ConfigurableEnvironment configurableEnvironment = context.getEnvironment(); return configurableEnvironment.getProperty(PropertyName); } }
2.3.5)TestGetProperties測(cè)試類:測(cè)試獲取屬性值
package com.icbc.app.runner; import com.icbc.app.config.SpringUtil; import com.icbc.app.config.TaskConfig; import com.icbc.app.config.TestTaskConfig; import org.springframework.stereotype.Component; import java.util.ResourceBundle; @Component public class TestGetProperties { public void run(String... args) throws Exception { //第一種:獲取系統(tǒng)環(huán)境的 systemTime 值 System.out.println("系統(tǒng)值systemTime=" + System.getenv("CALLTIME")); //第二種:ResourceBundle獲取testConfig配置文件的的 name 值 ResourceBundle bundle = ResourceBundle.getBundle("testConfig"); String name = bundle.getString("name"); System.out.println("ResourceBundle獲取name值=" + name); //第三種:TaskConfig.properties的sleepTime值 String sleepTime = SpringUtil.getProperty(TaskConfig.class, "sleepTime"); System.out.println("TaskConfig.properties的sleepTime值="+sleepTime); //第四種:TestTaskConfig.properties文件的Time值 String time = SpringUtil.getProperty(TestTaskConfig.class, "Time"); System.out.println("TestTaskConfig.properties文件的Time值="+time); } }
第三章、使用@Configurationproperties注解
@Configurationproperties(prefix=”xxx”)prefix的作用是區(qū)分同名配置,如果不指定,那么會(huì)去配置文件中尋找與該類的屬性名一致的配置文件。
prefix怎么使用呢?
在生產(chǎn)環(huán)境配置文件applicatin-product.properties中,有自定義的三個(gè)school前綴的配置項(xiàng)
在核心配置文件applicatin.properties中激活生產(chǎn)環(huán)境,這里的product對(duì)應(yīng)文件名application-produc的橫杠后面的produc
當(dāng)指定prefix之后,就不需要再在屬性上面搭配@value注解使用,因?yàn)楫?dāng)指定前綴school之后,屬性就會(huì)自動(dòng)注入
第四章、使用Java Properties類
Properties prop = new Properties(); try (InputStream input = new FileInputStream("config.properties")) { prop.load(input); String dbUrl = prop.getProperty("db.url"); String dbUser = prop.getProperty("db.user"); String dbPassword = prop.getProperty("db.password"); // 使用讀取到的屬性進(jìn)行后續(xù)操作 } catch (IOException ex) { ex.printStackTrace(); }
第五章、使用Environment接口
配置文件如圖:
獲取配置文件中的屬性值:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class MyComponent { public static String Value1 ; public static String Value2 ; @Autowired private Environment environment; public void getPropertyFromEnvironment() { Value1 = environment.getProperty("school.name"); Value2 = environment.getProperty("school.buile.age"); System.out.println("Value1: " + Value + "Value1: "+Value2 ); } }
第六章、使用ResourceBundle類
新建一個(gè)配置文件:ResourceBunTest.properties,信息如下圖
使用ResourceBundle類獲取配置文件內(nèi)容
public class ResourceBundleTest { public static void main(String[] args) { testResoBund(); } //獲取配置文件信息的方法 public static void testResoBund(){ //根據(jù)配置文件名稱獲得ResourceBundle 對(duì)象 ResourceBundle bundle = ResourceBundle.getBundle("ResourceBunTest"); String userId = bundle.getString("userId"); String userName = bundle.getString("userName"); String age = bundle.getString("age"); System.out.println(userId+"---"+userName+"---"+age); } }
測(cè)試結(jié)果:獲取成功
到此這篇關(guān)于springboot中獲取配置文件中屬性值的幾種方式小結(jié)的文章就介紹到這了,更多相關(guān)springboot獲取配置文件屬性值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Jenkins源代碼管理SVN實(shí)現(xiàn)步驟解析
這篇文章主要介紹了Jenkins源代碼管理SVN實(shí)現(xiàn)步驟解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Spring?Data?Elasticsearch?5.x實(shí)現(xiàn)單詞糾錯(cuò)和自動(dòng)補(bǔ)全
這篇文章主要為大家介紹了Spring?Data?Elasticsearch?5.x實(shí)現(xiàn)單詞糾錯(cuò)和自動(dòng)補(bǔ)全示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08通過springboot+mybatis+druid配置動(dòng)態(tài)數(shù)據(jù)源
這篇文章主要介紹了通過springboot+mybatis+druid配置動(dòng)態(tài)數(shù)據(jù)源,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06Mybatis-plus selectByMap條件查詢方式
這篇文章主要介紹了Mybatis-plus selectByMap條件查詢方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06MyBatis中的SQL映射文件如何配置參數(shù)映射和使用方法
MyBatis 是一種開源的 Java 持久化框架,它可以自動(dòng)將數(shù)據(jù)庫中的數(shù)據(jù)映射到 Java 對(duì)象中,并且使得 Java 對(duì)象可以非常方便地存儲(chǔ)到數(shù)據(jù)庫中,本文將介紹 MyBatis 中 SQL 映射文件的參數(shù)映射配置和使用方法,需要的朋友可以參考下2023-07-07Kafka單機(jī)多broker實(shí)例集群搭建教程詳解
Apache?Kafka?是一個(gè)分布式流處理平臺(tái),廣泛應(yīng)用于日志收集、監(jiān)控?cái)?shù)據(jù)聚合等,本文將詳細(xì)介紹如何在一個(gè)單機(jī)上搭建多個(gè)Kafka?Broker實(shí)例的步驟,希望對(duì)大家有所幫助2025-03-03Java 實(shí)戰(zhàn)項(xiàng)目之畢業(yè)設(shè)計(jì)管理系統(tǒng)的實(shí)現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實(shí)現(xiàn)畢業(yè)設(shè)計(jì)管理系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2021-11-11Java實(shí)現(xiàn)解析JSON大文件JsonReader工具詳解
這篇文章主要介紹了Java實(shí)現(xiàn)解析JSON大文件的工具JsonReader使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01