如何使用注释注入一个值,构造豆 [英] How to inject a value to bean constructor using annotations

查看:132
本文介绍了如何使用注释注入一个值,构造豆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Spring bean有一个独特的强制性参数的构造函数,我设法使用XML配置来初始化:

My spring bean have a constructor with an unique mandatory argument, and I managed to initialize it with the xml configuration :

<bean name="interfaceParameters#ota" class="com.company.core.DefaultInterfaceParameters">
  <constructor-arg>
    <value>OTA</value>
  </constructor-arg>
 </bean>

然后我用这个bean这样的,它工作得很好。

Then I use this bean like this and it works well.

 @Resource(name = "interfaceParameters#ota")
 private InterfaceParameters interfaceParameters;

不过,我想指定与annocations的构造器ARG值,像

But I would like to specify the contructor arg value with the annocations, something like

 @Resource(name = "interfaceParameters#ota")
 @contructorArg("ota") // I know it doesn't exists!
 private InterfaceParameters interfaceParameters;

这可能吗?

在此先感谢

推荐答案

首先,你必须在你的bean定义指定构造阿根廷,而不是在你的注入点。然后,你可以使用Spring的 @Value 注释(春季3.0)

First, you have to specify the constructor arg in your bean definition, and not in your injection points. Then, you can utilize spring's @Value annotation (spring 3.0)

@Component
public class DefaultInterfaceParameters {

    @Inject
    public DefaultInterfaceParameters(@Value("${some.property}") value) {
         // assign to a field.
    }
}

但是,请注意在构造函数注入春天皱眉。你最好在注入豆字段的值。

However, note that spring frowns upon constructor injection. You'd better inject values in beans fields.

据我看到的问题,这可能并不适合你,因为你似乎定义相同类的多个豆类,名称不同。对于您不能使用注解,你必须在XML来定义这些。

As far as I see the problem, this might not suit you, since you appear to define multiple beans of the same class, named differently. For that you cannot use annotations, you have to define these in XML.

不过,我不认为这是一个好主意,有这些不同的豆子。你几乎只有更好使用的字符串值。但我不能提供更多的信息,因为我不知道你的确切类。

However I do not think it is such a good idea to have these different beans. Youd better use only the string values. But I cannot give more information, because I dont know your exact classes.

这篇关于如何使用注释注入一个值,构造豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆