简体   繁体   English

使用Spring容器在非spring对象上调用方法,以允许参数接线吗?

[英]Invoke a method on a non-spring object with Spring container, allowing parameter wirings?

I have an object that is created outside of the container. 我有一个在容器外部创建的对象。 This object has one method accept(...) . 该对象具有一个方法accept(...) Note that this is not an interface method, as the number and the type of the parameters are unknown. 请注意,这不是接口方法,因为参数的数量和类型未知。

Anyhow, I have also the Method of the accept() method. 总之,我也是Method中的accept()方法。

I would like to execute this method within the Spring application context, allowing Spring to auto-wire method parameters before running the method. 我想在Spring应用程序上下文中执行此方法,从而允许Spring在运行方法之前自动关联方法参数。

Example: 例:

public class MyCmd {
    public long accept(@AutoWire MyService service) {
    ...
    }
}

and later: 然后:

MyCmd cmd = new MyCmd();     // no spring here!
magicRunner.invoke(cmd);     // magic here

Here I want to be able to run accept() , but to let the Spring to inject the MyService as an argument for the method. 在这里,我希望能够运行accept() ,但要让Spring注入MyService作为方法的参数。

Is there anything like this in Spring? 春天有这样的事情吗? Or I have to do all this manually? 还是我必须手动执行所有这些操作?

I think that this is hardly doable to mix reflection and Spring autowiring through method arguments, but still there is an approach that looks equivalent to what you are trying to achieve (if I understand it properly). 我认为将反射和Spring自动装配通过方法参数混合起来几乎是不可能的,但是仍然有一种方法看起来与您要实现的目标等效(如果我正确理解的话)。

MyCmd can be registered with "prototype" scope in the AplicationContext . MyCmd可以在“原型”的范围进行登记AplicationContext It will be autowired with other existing Spring beans, but a new instance will be returned each time you look for it in the context: 它将与其他现有的Spring Bean自动连接,但是每次在上下文中查找它时,都会返回一个新实例:

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Data
public class MyCmd {

  @Autowired
  private MyService myService;

  public long accept() {
    // ...
  }

}

Now, when you need to use MyCmd : 现在,当您需要使用MyCmd

  @Autowired
  private ApplicationContext applicationContext;

  public void doMyThings() {
    MyCmd myCmd = applicationContext.getBean(MyCmd.class);
    // myCmd is a new ref each time, myService is autowired inside
    magicRunner.invoke(cmd);  
  }

Yes you can use @Configurable to dependency inject domain objects in Spring employing AspectJ. 是的,您可以在使用AspectJ的Spring中使用@Configurable来依赖注入域对象。

Here's the documentation on @Configurable. 这是@Configurable上的文档。

Example with constructor DI: 构造函数DI的示例:

@Configurable
public class MyCmd {

    @Autowired
    public MyCmd(MyService service) {
      ...
    }
}

But beware: from that point on this is a Spring-managed bean so you cannot instantiate it as: 但要注意:从那时起,这是一个Spring管理的bean,因此您不能将其实例化为:

MyCmd cmd = new MyCmd();

But rather you'll have to Dependency Inject it as usual. 但是,您必须像往常一样依赖注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM