Spring注解@Autowired和@resource的区别
2017-02-14 10:58
351 查看
Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy。
@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
package com.xmm.demo.service.imp; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xmm.demo.dao.BaseDAO; import com.xmm.demo.domain.Emp; import com.xmm.demo.service.EmpService; @Transactional //启用事务机制 @Service("empService") public class EmpServiceImpl implements EmpService { @Resource private BaseDAO<Emp> baseDAO; @Override public void saveEmp(Emp emp) { baseDAO.save(emp); } @Override public void updateEmp(Emp emp) { baseDAO.update(emp); } @Override public Emp findEmpById(int id) { return baseDAO.get(Emp.class, id); } @Override public void deleteEmp(Emp emp) { baseDAO.delete(emp); } @Override public List<Emp> findAllList() { return baseDAO.find("from Emp"); } }
相关文章推荐
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中 @Autowired注解与@Resource注解的区别
- Spring @Resource、@Autowired、@Qualifier的注解注入及区别
- Spring中@Autowired注解、@Resource注解的区别
- spring中@Autowired注解、@resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解,@Resource注解和xml default-autowire区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别
- Spring中@Autowired注解、@Resource注解的区别