在面试中,谈及Spring框架的IOC时,经常会被问及@Resource与@Autowired的区别。
相同点:
- @Resource和@Autowired都是做bean的依赖注入时使用;
不同点:
来源不同:
- @Autowired为Spring提供的注解。需要导入包org.springframework.beans.factory.annotation.Autowired。
- @Resource由J2EE提供,需要导入包javax.annotation.Resource。
装配类型不同:
- @Autowired注解是按照类型(byType)装配依赖对象。默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。
- @Resource注解默认按照名称(byName)装配依赖对象。
@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。