如何使用注释将值注入bean构造函数

tbr*_*lle 27 spring annotations

我的spring bean有一个带有唯一强制参数的构造函数,我设法用xml配置初始化它:

<bean name="interfaceParameters#ota" class="com.company.core.DefaultInterfaceParameters">
  <constructor-arg>
    <value>OTA</value>
  </constructor-arg>
 </bean>
Run Code Online (Sandbox Code Playgroud)

然后我像这样使用这个bean,效果很好.

 @Resource(name = "interfaceParameters#ota")
 private InterfaceParameters interfaceParameters;
Run Code Online (Sandbox Code Playgroud)

但我想用annocations指定构造函数arg值,类似于

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

这可能吗 ?

提前致谢

Boz*_*zho 65

首先,您必须在bean定义中指定构造函数arg,而不是在注入点中指定.然后,你可以使用spring的@Value注释(春季3.0)

@Component
public class DefaultInterfaceParameters {

    @Inject
    public DefaultInterfaceParameters(@Value("${some.property}") String value) {
         // assign to a field.
    }
}
Run Code Online (Sandbox Code Playgroud)

这也是鼓励的,因为Spring建议在现场注入时进行构造器注入.

就我看到的问题而言,这可能不适合你,因为你似乎定义了同一个类的多个bean,命名方式不同.为此你不能使用注释,你必须在XML中定义它们.

但是我不认为拥有这些不同的bean是个好主意.你最好只使用字符串值.但我不能提供更多信息,因为我不知道你的确切类别.

  • >"春天对构造函数注入皱眉"......不确定你的参考,但是这篇Spring博客文章(http://spring.io/blog/2007/07/11/setter-injection-versus-constructor-injection并且使用了必需的/)说:"我们通常建议人们对所有强制性协作者使用构造函数注入,并为所有其他属性使用setter注入." 当然,当我为SpringSource工作时,没有皱眉头. (28认同)