Springboot在有參構(gòu)造方法類中使用@Value注解取值
我們在Springboot中經(jīng)常使用@Value注解來獲取配置文件中的值,像下面這樣
@Componentclass A { @Value('${user.value}') private String configValue; public void test() { System.out.println(configValue); }}
但有時我們需要這個類擁有一個有參的構(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進行管理,而不能使用new去實例化對象,否則@Value取值為NULL。我們一般使用@Autowired都是默認注入無參的構(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)用時,只需要獲取到對應(yīng)的Bean
A a = (A) SpringUtil.getBean('abc');a.test();
就可以同時獲取到配置文件中的值和傳入的參數(shù)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動態(tài)(可拖動控件大小)布局控件QSplitter詳細使用方法與實例2. vue跳轉(zhuǎn)頁面常用的幾種方法匯總3. 不要在HTML中濫用div4. ASP 處理JSON數(shù)據(jù)的實現(xiàn)代碼5. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)6. CSS清除浮動方法匯總7. XML 非法字符(轉(zhuǎn)義字符)8. 父div高度不能自適應(yīng)子div高度的解決方案9. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)10. XML入門的常見問題(三)
