springboot中獲取配置文件中屬性值的幾種方式小結(jié)
第一章、使用@Value注解
①@Value注解用于獲取配置文件中的屬性定義并綁定到Java Bean或?qū)傩灾?。在核心配置文件applicatin.properties中,添加兩個自定義配置項school.name和school.website。

②在SpringBootController中定義屬性,并使用@Value注解或者自定義配置值,并對其方法進行測試
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 可以在類路徑下找到并加載這個coremail.properties屬性文件。需要再在屬性上面搭配@value注解使用其中定義的屬性值。

2.2)指定文件路徑,在屬性上添加@Value注解

2.3)使用ApplicationContextAware接口來獲得TConfig中對應(yīng)properties文件的屬性值
2.3.1)TaskConfig類與TestTaskConfig類
有兩個配置文件,使用兩個config類指定properties類文件路徑

@Configuration//當(dāng)一個類被標(biāo)注了@Configuration注解時,Spring會將這個類識別為配置類,
// 用于定義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)啟動類:啟動只運行一次
//@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類實現(xiàn)ApplicationContextAware接口
通過實現(xiàn)ApplicationContextAware接口獲取ApplicationContext對象,來獲得TaskConfig中對應(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測試類:測試獲取屬性值
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ū)分同名配置,如果不指定,那么會去配置文件中尋找與該類的屬性名一致的配置文件。
prefix怎么使用呢?
在生產(chǎn)環(huán)境配置文件applicatin-product.properties中,有自定義的三個school前綴的配置項

在核心配置文件applicatin.properties中激活生產(chǎn)環(huán)境,這里的product對應(yīng)文件名application-produc的橫杠后面的produc

當(dāng)指定prefix之后,就不需要再在屬性上面搭配@value注解使用,因為當(dāng)指定前綴school之后,屬性就會自動注入

第四章、使用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");
// 使用讀取到的屬性進行后續(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類
新建一個配置文件:ResourceBunTest.properties,信息如下圖

使用ResourceBundle類獲取配置文件內(nèi)容
public class ResourceBundleTest {
public static void main(String[] args) {
testResoBund();
}
//獲取配置文件信息的方法
public static void testResoBund(){
//根據(jù)配置文件名稱獲得ResourceBundle 對象
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);
}
}
測試結(jié)果:獲取成功

到此這篇關(guān)于springboot中獲取配置文件中屬性值的幾種方式小結(jié)的文章就介紹到這了,更多相關(guān)springboot獲取配置文件屬性值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Data?Elasticsearch?5.x實現(xiàn)單詞糾錯和自動補全
這篇文章主要為大家介紹了Spring?Data?Elasticsearch?5.x實現(xiàn)單詞糾錯和自動補全示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
通過springboot+mybatis+druid配置動態(tài)數(shù)據(jù)源
這篇文章主要介紹了通過springboot+mybatis+druid配置動態(tài)數(shù)據(jù)源,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,,需要的朋友可以參考下2019-06-06
Mybatis-plus selectByMap條件查詢方式
這篇文章主要介紹了Mybatis-plus selectByMap條件查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
MyBatis中的SQL映射文件如何配置參數(shù)映射和使用方法
MyBatis 是一種開源的 Java 持久化框架,它可以自動將數(shù)據(jù)庫中的數(shù)據(jù)映射到 Java 對象中,并且使得 Java 對象可以非常方便地存儲到數(shù)據(jù)庫中,本文將介紹 MyBatis 中 SQL 映射文件的參數(shù)映射配置和使用方法,需要的朋友可以參考下2023-07-07
Java 實戰(zhàn)項目之畢業(yè)設(shè)計管理系統(tǒng)的實現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)畢業(yè)設(shè)計管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11
Java實現(xiàn)解析JSON大文件JsonReader工具詳解
這篇文章主要介紹了Java實現(xiàn)解析JSON大文件的工具JsonReader使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

