简体   繁体   English

如何使用注释对Spring执行基于构造函数的依赖注入?

[英]How do I perform Constructor-based dependency injection with Spring using annotations?

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;
}

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? 例如,我在这里定义superBean有限定符“SuperBean”,但我也想知道如何使用注释在这里设置名称值?

I know it's possible with xml configuration, but I want to know how to do this with annotations too: 我知道有可能使用xml配置,但我想知道如何使用注释执行此操作:

<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>

Well how do I put in values for String, int and other generic types? 那么我如何为String,int和其他泛型类型输入值?

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
    } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM