[OCP 17 book] | [OCP 11 book] | [OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Thanks, lots of things were going throw my mind and I skipped this simple concept.Jeanne Boyarsky wrote:3) A constructor is run when an object is instantiated. This means the only opportunity for a constructor to run is before the object is ready for use by other methods. Which means the constructor injection needs to happen before the setter.
Yes I tried it and intent is to do all three on the same field, actually just for better understanding of bean injection, not in general programming.Jeanne Boyarsky wrote:2) Try it? The intent is to do all three on the same field
My question was: like setter autowire inject bean using a setter method, constructor autowire uses a constructor then how the bean is injected in case of member variable autowiring? I hope now my question makes sense.Jeanne Boyarsky wrote:1) I don't understand the question. Spring injects it for you.
Stephan van Hulst wrote:I agree with Peter. You should pretty much always prefer constructor injection.
I agree with Peter. you should pretty much always prefer constructor injection.
Just to add (in IMHO) its best not to use field injection as it makes writing test cases awkward.
I write about Java & Spring @ https://www.marcobehler.com/guides
Puspender Tanwar wrote:but there are some posts that advise using setter injection over constructor injection.
How not to hate Spring 2016
Injection
Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies. For more background on why field based injection is evil, you can read this article by Oliver Gierke.
As always there is one exception to the rule, it’s fine to use field-based injection in tests when you’re using the SpringJUnit4ClassRunner.
.....
Testing
The golden rule for unit testing in Spring is keep Spring out of your unit testing! It should be possible to unit test the majority of your beans without needing to spin up an application context.
Regards Pete
Stephan van Hulst wrote:
Puspender Tanwar wrote:but there are some posts that advise using setter injection over constructor injection.
Please show us where you read that.
Don't get me started about those stupid light bulbs. |