Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new object and call a method spring configuration

Tags:

java

spring

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

new MyObject().getData()

instead of

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

I know how to do it in 2nd 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 must be a way to do this in a single definition. Please suggest.

like image 651
sravanreddy001 Avatar asked Jan 13 '23 18:01

sravanreddy001


2 Answers

Have you considered using an anonymous bean in your 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 for the fact that there is no intermediate bean definition. I am not sure whether or not the MyObject instance will be in your ApplicationContext, though, so if you need it there, you may want to look into that.

like image 59
nicholas.hauschild Avatar answered Jan 23 '23 01:01

nicholas.hauschild


You could try with @Autowire.

In the classes where you need the MyObject bean, you could use something like this:

public class MyClass {

      @Autowire
      MyObject myObject;

      public void myMethodofMyClass(){
         myObject.oneMethodOfMyObject();
      }

}

You can find more info in the spring reference manual (page 54).

like image 39
Piero Divasto Avatar answered Jan 23 '23 02:01

Piero Divasto