In previous blog we saw Dependency Injection in Spring using XML.
Here we will see how we can do same using Annotation
Construction Injection using Annotation
- In xml we are telling Spring to look for a package to scan for Annotation based configurations like in this case @Component and @Autowired .
- @Autowired above Car is way of injecting Bean as a Constructor
Setter Injection using Annotation
- Only change will be in Car class, the way we inject object.
- Instead of autowiring Constructor we are using a setter method autowiring.
- Other piece of code remains same.
- To use annotation based injection we need to define base package full path of class in xml.
- Use @Component, @Autowired for Objects we need to inject.
- You can get the code used above here. Just look for com.main.spring.annotation package.