We have seen Autowiring by Annotations using application.xml. But this time we will not be using application.xml at all. Rather replace it using java.
Also we have seen Autowiring can be achieved with annotations using the @Autowired annotation.
We will be taking the same classes 'Car' and 'Wheel', where 'Car' class has a reference to an instance of 'Wheel' class. Let us define the classes with annotations. Also let us assume all the classes are in 'com.learnerslesson' package.
Since, we have marked the 'Wheel' class with '@Component', Spring creates a 'Wheel' bean and with '@Value("Solid Tire")' it assignes a value 'Solid Tire' to the 'tire' property of 'Wheel'.
With '@Component("car")', Spring creates a 'Car' bean with name 'car'.
Now, with '@Autowired' annotation Spring searches for a bean of 'Wheel' type. And since the 'Wheel' bean is already there, Spring injects the 'Wheel' bean to the 'Car' class.
Thats all you need to do to get the Autowiring done.
Finally, we can write the application-config.xml
And the replacement class for 'application-context.xml' is defined below :
So, we have used @Configuration above the 'JavaAppConfig'. Which informs spring that it should be treated as a Configuration class(Or a replacement for application-context.xml).
And the body of the class is completely blank. It is all because of
It scans for all the beans annotated with @Component, creates beans and keeps in its container.And in 'Car' bean it finds @Autowired on top of 'Wheel wheel',
It searches for 'Wheel' bean and injects in the reference of 'Wheel' that 'Car' is holding.
Finally, in the main() method we define our application code to interact with spring.