共同点:
两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法。
不同点:
1、@Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。@Autowired注解是按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。
2、@Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。
关于写在字段上和写在方法上
@Resource(name="personDaoBean")
private PersonDao personDao; // 用于字段上
@Resource
public void setPersonDao(PersonDao personDao) { // 用于属性的setter方法上
this.personDao = personDao;
}