【问题标题】:How to inject a value to bean constructor using annotations如何使用注解将值注入 bean 构造函数
【发布时间】:2011-05-11 08:07:28
【问题描述】:

我的 spring bean 有一个带有唯一强制参数的构造函数,我设法使用 xml 配置对其进行了初始化:

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

然后我就这样用这个bean,效果很好。

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

但我想用 annocations 指定构造函数 arg 值,例如

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

这可能吗?

提前致谢

【问题讨论】:

  • 或许答案给了here

标签: spring annotations


【解决方案1】:

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

@Component
public class DefaultInterfaceParameters {

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

This is also encouraged as Spring advises constructor injection over field injection.

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

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

【讨论】:

  • 感谢您的回复,“仅使用字符串值”是什么意思?
  • 好吧,您需要“OTA”字符串。你不需要一个完整的对象。
  • 哦,我明白了,我的 bean 的 @postConstruct 方法中使用了“OTA”字符串,它是构建 bean 的必需信息。该字符串用于从数据库中检索数据。这种类型的每个 bean 将为每个字符串值返回不同的数据。顺便说一句,你对 xml 的使用是正确的,因为我为同一个类定义了多个 bean,我不能使用注释。
  • > "spring frowns on constructor injection" ...不确定您对此的参考,但这篇 Spring 博客文章 (spring.io/blog/2007/07/11/…) 说“我们通常建议人们对所有强制使用构造函数注入所有其他属性的协作者和设置器注入。”当然,当我为 SpringSource 工作时,没有皱眉。
  • 你为什么使用@inject 而不是@autowired?
【解决方案2】:

正如 Bozho 所说,您可以设置属性,而不是构造函数 arg...@PostConstruct 只会在设置所有属性后才被调用...所以,您仍然可以使用您的字符串...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多