久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Springboot在有參構造方法類中使用@Value注解取值

瀏覽:2日期:2023-05-08 15:55:09

我們在Springboot中經常使用@Value注解來獲取配置文件中的值,像下面這樣

@Componentclass A { @Value('${user.value}') private String configValue; public void test() { System.out.println(configValue); }}

但有時我們需要這個類擁有一個有參的構造方法,比如

@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都是默認注入無參的構造方法,要想注入有參的構造方法,我們需要構建Config類:

@Configurationpublic class AConfig { @Bean(name='abc') DataOpration abcA() { return new A('abc'); }}

然后創建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); }}

在調用時,只需要獲取到對應的Bean

A a = (A) SpringUtil.getBean('abc');a.test();

就可以同時獲取到配置文件中的值和傳入的參數。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 旬邑县| 安阳市| 叙永县| 泗阳县| 桦甸市| 马尔康县| 定远县| 洛阳市| 萍乡市| 葫芦岛市| 息烽县| 四子王旗| 岢岚县| 天祝| 留坝县| 郁南县| 南京市| 大方县| 衢州市| 凤庆县| 万年县| 达日县| 六安市| 光泽县| 灵山县| 正定县| 浮梁县| 肥城市| 嵩明县| 平罗县| 辽源市| 子洲县| 惠东县| 普定县| 余干县| 玛曲县| 綦江县| 景德镇市| 博乐市| 昌都县| 钟祥市|