Springboot在有參構(gòu)造方法類中使用@Value注解取值
我們?cè)赟pringboot中經(jīng)常使用@Value注解來獲取配置文件中的值,像下面這樣
@Component
class A {
@Value("${user.value}")
private String configValue;
public void test() {
System.out.println(configValue);
}
}
但有時(shí)我們需要這個(gè)類擁有一個(gè)有參的構(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í)例化對(duì)象,否則@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)用時(shí),只需要獲取到對(duì)應(yīng)的Bean
A a = (A) SpringUtil.getBean("abc");
a.test();
就可以同時(shí)獲取到配置文件中的值和傳入的參數(shù)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot logback-spring.xml無法加載問題
這篇文章主要介紹了Springboot logback-spring.xml無法加載問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Spring MVC的項(xiàng)目準(zhǔn)備和連接建立方法
SpringWebMVC是基于Servlet API的Web框架,屬于Spring框架的一部分,主要用于簡(jiǎn)化Web應(yīng)用程序的開發(fā),SpringMVC通過控制器接收請(qǐng)求,使用模型處理數(shù)據(jù),并通過視圖展示結(jié)果,感興趣的朋友跟隨小編一起看看吧2024-10-10
Java多線程CyclicBarrier的實(shí)現(xiàn)代碼
CyclicBarrier可以使一定數(shù)量的線程反復(fù)地在柵欄位置處匯集,本文通過實(shí)例代碼介紹下Java多線程CyclicBarrier的相關(guān)知識(shí),感興趣的朋友一起看看吧2022-02-02
SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper實(shí)例詳解
這篇文章主要介紹了SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper實(shí)例詳解 ,需要的朋友可以參考下2017-09-09
mybatis-plus與mybatis共存的實(shí)現(xiàn)
本文主要介紹了mybatis-plus與mybatis共存的實(shí)現(xiàn),文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

