Springboot在有參構(gòu)造方法類中使用@Value注解取值
我們?cè)赟pringboot中經(jīng)常使用@Value注解來獲取配置文件中的值,像下面這樣
@Componentclass A { @Value('${user.value}') private String configValue; public void test() { System.out.println(configValue); }}
但有時(shí)我們需要這個(gè)類擁有一個(gè)有參的構(gòu)造方法,比如
@Componentclass 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類:
@Configurationpublic class AConfig { @Bean(name='abc') DataOpration abcA() { return new A('abc'); }}
然后創(chuàng)建SpringUtil類
@Componentpublic 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í)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. XHTML 1.0:標(biāo)記新的開端5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. 利用CSS3新特性創(chuàng)建透明邊框三角7. XML入門的常見問題(四)8. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼9. 詳解CSS偽元素的妙用單標(biāo)簽之美10. HTML5 Canvas繪制圖形從入門到精通
