我们在Springboot中经常使用@Value注解来获取配置文件中的值,像下面这样
1 2 3 4 5 6 7 8 9 | @Component class A { @Value ( "${user.value}" ) private String configValue; public void test() { System.out.println(configValue); } } |
但有时我们需要这个类拥有一个有参的构造方法,比如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @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进行管理,而不能使用new去实例化对象,否则@Value取值为NULL。我们一般使用@Autowired都是默认注入无参的构造方法,要想注入有参的构造方法,我们需要构建Config类:
1 2 3 4 5 6 7 | @Configuration public class AConfig { @Bean (name= "abc" ) DataOpration abcA() { return new A( "abc" ); } } |
然后创建SpringUtil类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @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); } } |
在调用时,只需要获取到对应的Bean
A a = (A) SpringUtil.getBean("abc");
a.test();
就可以同时获取到配置文件中的值和传入的参数。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/189603/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)