1.@Autowired只按照类型注入,不匹配name进行注入。而@Resource就比较灵活,默认的话按照name匹配(即示例中的bean的id),@Resource可以通过配置它的两个属性:name和type来指定按照类型还是名称注入,不指定默认按照name注入,一般来说@Autowired用在实现类上。
下面说说将@Resource用在实现类里会出现的问题
比如我有两个Mapper
@Mapper
public interface Cs1Mapper {
}
@Mapper
public interface CsMapper {
}
然后我的实现类里这样写,注入的是Cs1Mapper 但是名字又写成这样csMapper
public interface CsService {
}
@Service
public class Cs1ServiceImpl implements Cs1Service {
@ResourceCs1Mapper csMapper;
}
启动的时候就会报错
Description:The bean 'csMapper' could not be injected as a 'com.xxx.xxx.mapper.Cs1Mapper' because it is a JDK dynamic proxy that implements:Action:Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.
改成这样就能启动,因为@Autowired是根据type去找的
@Service
public class Cs1ServiceImpl implements Cs1Service {
@AutowiredCs1Mapper csMapper;
}