Dependency Injection in Spring With Annotations

@Autowired, @Resource, and @Inject are examples for annotations that are used for dependency injection in Spring.

While @Autowired is provided by the Spring framework, @Resource and @Inject are java standard annotations.

When using annotation-based dependency injection, if the dependency is not injected, we would get an exception at the startup of our application itself.

 

@Autowired annotation

@Autowired does dependency injection based on name, type etc. without explicitely defining dependencies. You can learn more about autowiring with example @ bean-autowiring-in-spring.

 

@Resource annotation

Similarly @Resource does automatic dependency injection based on the name of the property (if @Resource is used without any parameters) or based on the name you specify as @Resource (name= "dependent-bean-name").

 

@Component and @ComponentScan Annotations

@Component annotation can be used to tell Spring that a class is a bean without declaring it as a bean in the spring xml. 

 

You can enable component-scanning,from code using the ComponentScan annotation:

@ComponentScan(basePackages = {

"com.javajee.spring1",

 "com.javajee.spring2"

})

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!