java - Spring Autowire 属性对象

标签 java spring autowired

我已经为除 java.util.Properties 实例之外的所有内容成功配置了 Spring Autowiring 。

当我使用注释 Autowiring 其他所有内容时:

@Autowired private SomeObject someObject;

它工作得很好。

但是当我尝试这样做时:

@Autowired private Properties messages;

使用此配置:

<bean id="mybean" class="com.foo.MyBean" >
  <property name="messages">
    <util:properties location="classpath:messages.properties"/>
  </property>
</bean>

我收到错误(仅相关行):

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mybean' defined in class path resource [application.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'messages' of bean class [com.foo.MyBean]: Bean property 'messages' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Wheras,如果我用一个很好的老式 setter 方法尝试它,Spring 会很高兴地连接它:

public void setMessages(Properties p) {   //this works
  this.messages = p;
}

尝试 Autowiring 属性对象时我做错了什么?

最佳答案

看起来您正在尝试在第一种情况下调用 setter 方法。当您在 bean 元素内创建属性元素时,它将使用 setter 注入(inject)来注入(inject) bean。 (您的情况下没有 setter ,因此会引发错误)

如果你想 Autowiring 它删除这个:

<property name="messages">
    <util:properties location="classpath:messages.properties"/>
</property>

从 bean 定义中,因为这将尝试调用 setMessages 方法。

而是简单地将上下文文件中的属性 bean 单独定义为 MyBean:

<bean id="mybean" class="com.foo.MyBean" />
<util:properties location="classpath:messages.properties"/>

然后它应该会正确地 Autowiring 。

请注意,这也意味着您可以添加:@Autowired private Properties messages; 到任何 Spring 托管的 bean,以便在其他类中使用相同的属性对象。

关于java - Spring Autowire 属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15576303/

相关文章:

java - 我不明白Oracle文档中的这一部分?

java - 什么时候不使用 RxJava 的 Observable?

java - 如何用很少的属性绑定(bind)@Value?

使用 Spring Boot 时出现 Spring 批处理范围问题

java - 我可以在组件上使用 @Profile 标签而不在 Spring Boot 或 Web.xml 中创建 @Configuration 类吗

java - Spring中如何从@Autowired List<>的每个bean中获取@Qualifier

java - BeanFactoryAware VS。 @Autowired - Autowiring BeanFactory 是个坏主意吗?

java - 具有自定义类的 XmlPullParser 不显示所有 RSS 提要

java - 在 Spring Boot Eclipse 中使用多个外部 JAR

spring - Pentaho j_spring_security_check 混合内容。 HTTPS 到 HTTP