问题
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