java 创建一个新对象并调用一个方法spring配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15821037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:58:19  来源:igfitidea点击:

Create a new object and call a method spring configuration

javaspring

提问by sravanreddy001

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

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

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.

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

回答by nicholas.hauschild

Have you considered using an anonymous bean in your MethodInvokingFactoryBean?

你有没有考虑在你的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 MyObjectinstance will be in your ApplicationContext, though, so if you need it there, you may want to look into that.

这基本上等同于您所拥有的,除了没有中间 bean 定义这一事实。不过,我不确定该MyObject实例是否会在您的ApplicationContext.

回答by Piero Divasto

You could try with @Autowire.

你可以试试用@Autowire.

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

在需要MyObjectbean的类中,您可以使用以下内容:

public class MyClass {

      @Autowire
      MyObject myObject;

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

}

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

您可以在弹簧参考手册(第 54 页)中找到更多信息。