九、Spring注解:@Resource

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/liujun03/article/details/81872315
一、@Resource注解

​ @Resource注解与@Autowired注解一样,都可以用来自动装配bean。但我们要知道,@Autowired注解是属于Spring的,而@Resource注解是Java规范。@Resource注解也可以用在字段或者setter方法上。

  1. 写在字段上

    @Resource
    private ColorService colorService;

    或者

    @Resource(name = "blackColorServiceImpl")
    private ColorService colorService;
    注意事项:当@Resource注解写在字段上时,默认先使用名称进行匹配,名称可以通过@Resource的name属性指定,如上。当没有指定name属性的时候,则默认取字段名作为名称查找。当按名称找不到的时候,则按照字段的类型进行匹配。最后若还是没有找到,则报异常:
    nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException
  2. 写在setter方法上

    private ColorService colorService;
    
    @Resource
    public void setColorService(ColorService colorService) {
    this.colorService = colorService;
    }
    注意事项:当@Resource注解写在setter方法上的时候,先按照setter方法中参数名进行匹配,匹配不到的话,则按照参数类型进行匹配,若最后按类型匹配到多个或者一个都没有的话,则报异常。

猜你喜欢

转载自blog.csdn.net/liujun03/article/details/81872315