Springboot如何在有参构造方法类中使用@Value注解取值
小编给大家分享一下Springboot如何在有参构造方法类中使用@Value注解取值,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!
我们在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();
就可以同时获取到配置文件中的值和传入的参数。
看完了这篇文章,相信你对Springboot如何在有参构造方法类中使用@Value注解取值有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。