Can I combine manual instantiation with autowiring?

我的未来我决定 提交于 2019-12-12 03:45:36

问题


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?"

Concretely, say I have:

class A {

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

}

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;

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?


回答1:


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

One workaround that comes to my mind:

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.
}

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




回答2:


sunilkumar from vmoksha

NO we cant create like that



来源:https://stackoverflow.com/questions/15122622/can-i-combine-manual-instantiation-with-autowiring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!