Springboot在有參構(gòu)造方法類中使用@Value注解取值
我們在Springboot中經(jīng)常使用@Value注解來獲取配置文件中的值,像下面這樣
@Component
class A {
@Value("${user.value}")
private String configValue;
public void test() {
System.out.println(configValue);
}
}
但有時我們需要這個類擁有一個有參的構(gòu)造方法,比如
@Component
class A {
@Value("${user.value}")
private String configValue;
private String s;
public A(String s) {
this.s = s;
}
public void test() {
System.out.println(s);
System.out.println(configValue);
}
}
要使@Value生效,必須把Bean交給Spring進(jìn)行管理,而不能使用new去實(shí)例化對象,否則@Value取值為NULL。我們一般使用@Autowired都是默認(rèn)注入無參的構(gòu)造方法,要想注入有參的構(gòu)造方法,我們需要構(gòu)建Config類:
@Configuration
public class AConfig {
@Bean(name="abc")
DataOpration abcA() {
return new A("abc");
}
}
然后創(chuàng)建SpringUtil類
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通過name獲取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
}
在調(diào)用時,只需要獲取到對應(yīng)的Bean
A a = (A) SpringUtil.getBean("abc");
a.test();
就可以同時獲取到配置文件中的值和傳入的參數(shù)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringCloud使用feign調(diào)用錯誤的問題
這篇文章主要介紹了SpringCloud使用feign調(diào)用錯誤的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
SpringBoot使用JWT實(shí)現(xiàn)登錄驗證的方法示例
這篇文章主要介紹了SpringBoot使用JWT實(shí)現(xiàn)登錄驗證的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
spring Profile如何為不同環(huán)境提供不同的配置支持
這篇文章主要介紹了spring Profile如何為不同環(huán)境提供不同的配置支持,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
Java 本地方法Native Method詳細(xì)介紹
這篇文章主要介紹了 Java 本地方法Native Method詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-02-02
JAVA SpringBoot統(tǒng)一日志處理原理詳解
這篇文章主要介紹了SpringBoot的統(tǒng)一日志處理原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-09-09

