Kevin Simonson wrote:Is that all I need to know at the bottom of page 37, that Spring takes a variable declared with an interface, and instantiates it as a variable of an autowired bean that implements that interface? And what do I have to do to get this to happen? Does compiling class {CDPlayerConfig} cause Spring to autowire, or do I have to do something else with class {CDPlayerConfig}? I'm just trying to figure out what pages 1-37 are telling me.
Jesper de Jong wrote:So, how it works when you run your CDPlayerTest class using JUnit, is this:
JUnit sees the @RunWith annotation and creates a SpringJUnit4ClassRunner object to run the test The SpringJUnit4ClassRunner is a Spring-specific unit test runner, which creates the Spring application context, using the configuration that's specified with the @ContextConfiguration annotation on your test class Autowiring is done when the Spring application context is created It also does autowiring on your test class, so the member variable 'cd' of the test class is made to point to the bean that implements interface CompactDisc (which is a SgtPeppers object) Then the test methods in the CDPlayerTest class are executed, and they will have the CompactDisc bean to work with that has been autowired in the previous step.
What is very important to understand is that you must always get Spring beans from the Spring application context somehow. Never instantiate a Spring bean class using new, because then autowiring doesn't work - you'll just get a regular instance of the class on which Spring hasn't done its autowiring logic.
Jesper de Jong wrote:When you initialize the Spring application context, it will search for classes in the packages that you specified which have a @Component annotation (or a related annotation, such as @Service). It will create an instance of each of these classes, which is stored in the application context. It will also look for fields in those classes with an @Autowired annotation, and it will set these fields to other components that it has found.
In your example, this means it will indeed set the 'cd' member variable of your test class to a SgtPeppers object.
Hot dog! An advertiser loves us THIS much:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|