创建一个新对象并调用方法弹簧配置

sra*_*001 4 java spring

是否有一种在Spring xml配置文件中实现以下功能的捷径.

new MyObject().getData()
Run Code Online (Sandbox Code Playgroud)

代替

Object obj = new MyObject();
obj.getData();
Run Code Online (Sandbox Code Playgroud)

我知道如何在第二种情况下做到这一点.

<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>
Run Code Online (Sandbox Code Playgroud)

我相信必须有一种方法可以在一个单一的定义中做到这一点.请建议.

nic*_*ild 7

你有没有考虑过使用匿名豆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>
Run Code Online (Sandbox Code Playgroud)

除了没有中间bean定义这一事实外,这基本上等同于你拥有的内容.我不确定MyObject实例是否会在你的实例中ApplicationContext,所以如果你需要它,你可能想要研究一下.