如何在Spring中将依赖项注入自实例化对象? [英] How to inject dependencies into a self-instantiated object in Spring?

查看:144
本文介绍了如何在Spring中将依赖项注入自实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类:

  public class MyClass {
@Autowired private AnotherBean anotherBean;
}

然后我们创建了一个这个类的对象(或者一些其他框架创建了这个类的实例)。

  MyClass obj = new MyClass(); 

是否可以注入依赖项?如下所示:

  applicationContext.injectDependencies(obj); 

(我认为Google Guice有这样的东西)

解决方案

您可以使用 autowireBean()方法 AutowireCapableBeanFactory 。你传递一个任意的对象,Spring会像它自己创建的东西一样对待它,并且将应用各种自动装配的位和块。



要保持 AutowireCapableBeanFactory ,只是自动连线:

  private @Autowired AutowireCapableBeanFactory beanFactory; 

public void doStuff(){
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);
// obj现在将具有自动连线的依赖关系。
}


Let's say we have a class:

public class MyClass {
    @Autowired private AnotherBean anotherBean;
}

Then we created an object of this class (or some other framework have created the instance of this class).

MyClass obj = new MyClass();

Is it possible to still inject the dependencies? Something like:

applicationContext.injectDependencies(obj);

(I think Google Guice has something like this)

解决方案

You can do this using the autowireBean() method of AutowireCapableBeanFactory. You pass it an arbitrary object, and Spring will treat it like something it created itself, and will apply the various autowiring bits and pieces.

To get hold of the AutowireCapableBeanFactory, just autowire that:

private @Autowired AutowireCapableBeanFactory beanFactory;

public void doStuff() {
   MyBean obj = new MyBean();
   beanFactory.autowireBean(obj);
   // obj will now have its dependencies autowired.
}

这篇关于如何在Spring中将依赖项注入自实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆