一、@Resource注解
@Resource注解与@Autowired注解一样,都可以用来自动装配bean。但我们要知道,@Autowired注解是属于Spring的,而@Resource注解是Java规范。@Resource注解也可以用在字段或者setter方法上。
写在字段上
@Resource private ColorService colorService;或者
@Resource(name = "blackColorServiceImpl") private ColorService colorService;注意事项:当@Resource注解写在字段上时,默认先使用名称进行匹配,名称可以通过@Resource的name属性指定,如上。当没有指定name属性的时候,则默认取字段名作为名称查找。当按名称找不到的时候,则按照字段的类型进行匹配。最后若还是没有找到,则报异常:
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException写在setter方法上
private ColorService colorService; @Resource public void setColorService(ColorService colorService) { this.colorService = colorService; }注意事项:当@Resource注解写在setter方法上的时候,先按照setter方法中参数名进行匹配,匹配不到的话,则按照参数类型进行匹配,若最后按类型匹配到多个或者一个都没有的话,则报异常。
@Resource注解用于自动装配Java Bean,支持按名称和类型匹配。本文介绍@Resource注解的基本用法,包括其在字段和setter方法上的应用,并指出匹配过程中需要注意的事项。
852

被折叠的 条评论
为什么被折叠?



