I have successfully configured Spring autowiring for everything except instances of java.util.Properties.
When I autowire everything else with an annotation:
@Autowired private SomeObject someObject;
it works just fine.
But when I try this:
@Autowired private Properties messages;
with this configuration:
<bean id="mybean" class="com.foo.MyBean" >
<property name="messages">
<util:properties location="classpath:messages.properties"/>
</property>
</bean>
I get the error (relevant line only):
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, if I try it with a good old fashioned setter method, Spring wires it quite happily:
public void setMessages(Properties p) { //this works
this.messages = p;
}
What am I doing wrong when trying to autowire a properties object?
Looks like you are trying to call the setter method in the first case. When you create a property element inside a bean element it will use setter injection to inject the bean. (You dont have a setter in your case so it throws an error)
If you want to autowire it remove this:
<property name="messages">
<util:properties location="classpath:messages.properties"/>
</property>
From the bean definition as this will try to call a setMessages
method.
Instead simply define the properties bean in the context file separately to MyBean
:
<bean id="mybean" class="com.foo.MyBean" />
<util:properties location="classpath:messages.properties"/>
It should then autowire correctly.
Note this also means you can add this: @Autowired private Properties messages;
to any Spring managed bean to use the same properties object in other classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With