如何使用注解将值注入 bean 构造函数 [英] How to inject a value to bean constructor using annotations

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

问题描述

我的 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 定义中指定构造函数 arg,而不是在注入点中.然后,您可以利用 spring 的 @Value 注释(spring 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}") String value) {
         // assign to a field.
    }
}

这也受到鼓励,因为 Spring 建议构造函数注入而不是字段注入.

就我看到的问题而言,这可能不适合您,因为您似乎定义了同一个类的多个 bean,名称不同.因为你不能使用注解,你必须在 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. You'd better use only the string values. But I cannot give more information, because I dont know your exact classes.

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

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