Spring Autowire Property Object

I have successfully configured autwiring Spring for everything except java.util.Properties instances.

When I auto-install everything else using annotation:

@Autowired private SomeObject someObject; 

It works great.

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 an error (only the corresponding line):

 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? 

If I tried this with the old old-fashioned setter method, Spring would have laid it pretty happily:

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

What am I doing wrong when trying to auto-update a property object?

+4
source share
1 answer

It looks like you are trying to call the setter method in the first case. When you create a property element inside a bean, it will use setter injection to enter the bean. (You do not have a setter in your case, so that it throws an error)

If you want to auto-install it, delete this:

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

From the definition of bean, as this will try to call the setMessages method.

Instead, simply define the bean properties in the context file separately for MyBean :

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

Then it should automatically flash.

Please note that this also means that you can add this: @Autowired private Properties messages; in any Spring managed bean to use the same property object in other classes.

+8
source

All Articles