Specify the setter method name during dependency injection in Spring 3.0

I am preparing a bean that is present in one of the cans that I use.

The class has configuration methods that do not match the standard setter method names expected by the Spring framework to perform the injection (for example, the userName property has the setter addUserName method instead of setUserName ).

Is it possible to specify the name of the setter method during property injection?

+4
source share
3 answers

Perhaps this will be possible using the MethodInvokingFactoryBean class. With this, you can call the method on the target.

You create an object using Spring, and then call addUserName on it.

I'm not sure you can do this with annotations, but with XML you can. For instance:

 package some.pack; public class Target { private String userName; public Target() { ... } public void addUserName(String userName) { this.userName = userName; } ... } 

You can set the userName property in the Target instance with something like this:

 <!-- first create your Target object --> <bean id="target" class="some.pack.Target" /> <!-- then set the userName property by calling the non-conventional setter --> <bean id="caller" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="target" /> <property name="targetMethod" value="addUserName" /> <property name="arguments"> <list> <value>John_Doe</value> </list> </property> </bean> 

The disadvantage of this is that if you need to call several methods, you will need to add a β€œcalling” bean for each method. This will increase the size of the XML you must write.

Alternatively, you can use the adapter template to wrap your object in something that conforms to the getXXX / setXXX , and execute DI instead of the standard path on the wrapper.

+7
source

No I dont know.

You can auto-update annotation. You can use constructor injection.

I do not see a big advantage for breaking the standard, but I see a lot of disadvantages. What can damage your design if you break the ranks and call the method "setUsername"?

0
source

If you cannot change the code of the class you want to create, try using a static or instance factory, where factory is your code that can take the username as a parameter and call obj.addUsername (name).

0
source

All Articles