Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Autowire properties object

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?

like image 311
NickJ Avatar asked Feb 18 '23 01:02

NickJ


1 Answers

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.

like image 150
cowls Avatar answered Feb 28 '23 08:02

cowls