java - Spring @Autowired chains and regular 'new XYZ()' instantiations -
is impression correct using regular new xyz()
way of instantiating component xyz prevents spring processing @autowired
fields inside xyz?
second question: correct cannot use dependency injection in xyz , @ same time use final fields in xyz because of that? example:
@component public class xyz { @autowired private somedep dep; private final int value; public xyz(int value) { this.value = value; } }
how make working?
so, well, accepting there no nicer way, let's way:
@component public class xyz { @autowired private somedep dep; private final int value; // factory instantiation xyz() { value=0; } private xyz(somedep dep, int value) { this.dep = dep; this.value = value; } public xyz getinstance(int value) { return new xyz(dep, value); } }
??? ugly. , gets uglier when want move dependency declaration parent class....... ??? thought di nice. think have reconsider that. alternatives? missing something?
- if create object
new
, @autowired won't work, because object created outside of spring ioc container. object should instantiated spring in order let inject dependencies. object (bean) container (spring application context), should initialize spring context , callcontext.getbean("beanname")
. - you can use constructor dependency injection here. here can read more injection types
Comments
Post a Comment