我可以将手动实例化与自动装配相结合吗? [英] Can I combine manual instantiation with autowiring?

查看:289
本文介绍了我可以将手动实例化与自动装配相结合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.我不确定如何问这个问题,这是我必须丢失某些东西的迹象.我能做的最好的事情是:有没有一种方法可以手动实例化一个对象,并且仍然在该对象中使用注入?"

Ok. I am not sure how to even ask the question, which is the sign I must be missing something. The best I can do is: "Is there a way to instantiate an object manually and still use injection within that object?"

具体说我有:

class A {

   public A(MyObject1 obj1, MyObject2 obj2, ..., MyObjectn objn) {
     ...
   }

}

我想连接除MyObjectn之外的所有这些对象.据我所知,如果我在上述构造函数的前面使用@Autowired,那么我应该只在使用该类实例的代码中按以下方式实例化该对象:

I want to wire all of these objects except MyObjectn. As far as I know, if I use @Autowired in front of that constructor above, then I should only instantiate that object as follows in the code that uses an instance of that class:

@Autowired
A a;

这不允许我在构造函数中手动传递objn.除了在使用该类的实例的代码中手动初始化A之外,还有什么方法可以解决该限制?

which doesn't allow me to pass in objn in the constructor manually. Is there a way to get around that limitation short of manually initializing A in the code that uses an instance of that class?

推荐答案

简短答案-不. 您可以使用IoC或手动实例化对象.

Short answer - no. You either use an IoC or you manually instantiate Objects.

我想到一个解决方法:

创建每个MyObject1为@Autowired

Create a Service with every MyObject1 being @Autowired

在此服务内创建一个方法:

create a method inside this service:

public A createA(MyObjectN objn) {
   return new A(object1, object2... objn); //note that object1 .. objectn-1 are autowired.
}

使用@Autowired注入服务;)并调用service.createA()

Inject the service with @Autowired ;) and call service.createA()

这篇关于我可以将手动实例化与自动装配相结合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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