手动创建实例时如何在春季使@autowire工作 [英] How to make @autowire work in spring when creating instance manually

查看:76
本文介绍了手动创建实例时如何在春季使@autowire工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个Java接口,说ITest由两个类Class1和Class2实现.现在,我有一个工厂类,用于确定要返回的实现.就像


I have a java interface say ITest implemented by two classes Class1 and Class2. Now I have a factory class which I use to decide which implementation to return. like

if(something)
    return new Class1()
else
   return new Class2()

问题是我在Class1中没有自动实例化字段,但是在通过autowiring实例化的其他类中,同样的自动装配也可以工作.
这是Class1的代码

Problem is that I have autowired field in Class1 which doesn't get instantiated,, but the same autowiring works in other classes which were instantiated via autowiring.
Here is code for Class1

@Componene
public Class1 implements ITest{
  @Autowired
  private SomeClass obj;
}

不确定如何解决此问题.由于SomeClass的自动装配在其他类中工作正常.

Not sure how to get around this problem. As autowiring for SomeClass works fine in Other classes.

推荐答案

将applicationContext注入工厂类中,并用于创建bean:

Inject applicationContext in your factory class and use it for bean creation:

@Autowired private ApplicationContext applicationContext;
......
......
         if(something){
            return applicationContext.getBean("com.xyz.Class1");
         }
......
......

或者您可以在Class1和Class2的顶部使用@Configurable.这需要启用AspectJ编织.然后,当您使用new时,Spring将神奇地创建bean.

OR you can use @Configurable on top of Class1 and Class2. This needs AspectJ weaving to be enabled. Spring will then magically create beans when you use new.

这篇关于手动创建实例时如何在春季使@autowire工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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