如何使用注解通过Spring执行基于构造函数的依赖项注入? [英] How do I perform Constructor-based dependency injection with Spring using annotations?
本文介绍了如何使用注解通过Spring执行基于构造函数的依赖项注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,所以如果我需要在构造函数中放入一些原始值,该怎么做?
OK, so if I need to put some primitive values in the constructor, how do I do that?
@Autowired
public CustomBean(String name, @Qualifier("SuperBean") SuperBean superBean) {
super();
this.superBean = superBean;
this.name = name;
}
例如,在这里,我定义的是superBean具有限定符"SuperBean",但我也想知道如何在这里使用批注设置名称值?
For instance here I am defining that the superBean has the Qualifier "SuperBean", but I'd also like to know how is it possible to use annotations to set the name value here?
我知道使用xml配置是可行的,但是我也想知道如何使用注释来做到这一点:
I know it's possible with xml configuration, but I want to know how to do this with annotations too:
<bean id="CustomXmlBean" class="org.arturas.summerfav.beans.CustomXmlBean">
<constructor-arg name="name" type="String" value="The Big Custom XML Bean" />
<constructor-arg>
<bean id="SuperBean" class="org.arturas.summerfav.beans.SuperBean" />
</constructor-arg>
</bean>
那么如何为String,int和其他泛型类型输入值?
Well how do I put in values for String, int and other generic types?
推荐答案
这里是执行此操作的一种方法:
Here is one way to do this:
@Component
public class YourBean {
@Autowired
public YourBean(@Value("${prop1}") String arg1, @Value("${prop2}") String arg2) {
// rest of the code
}
}
这篇关于如何使用注解通过Spring执行基于构造函数的依赖项注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文