Create a new object and call the spring method

Is there a short way to implement the following functions in the Spring xml configuration file.

new MyObject().getData() 

instead

 Object obj = new MyObject(); obj.getData(); 

I know how to do this in the second case.

 <bean id="obj" class="MyObject" /> <bean id="data" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject"><ref local="obj" /></property> <property name="targetMethod"><value>getData</value></property> </bean> 

I am sure there should be a way to do this in one definition. Please suggest.

+4
source share
2 answers

Have you considered using an anonymous bean in a MethodInvokingFactoryBean ?

 <bean id="data" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject"><bean class="MyObject" /></property> <property name="targetMethod"><value>getData</value></property> </bean> 

This is basically equivalent to what you have, except that there is no intermediate definition of a bean. I'm not sure if there will be an instance of MyObject in your ApplicationContext , however, if you need it, you can look at it.

+7
source

You can try with @Autowire .

In classes where you need a MyObject bean, you can use something like this:

 public class MyClass { @Autowire MyObject myObject; public void myMethodofMyClass(){ myObject.oneMethodOfMyObject(); } } 

See the spring reference manual (page 54) for more information.

+1
source

All Articles