zoukankan      html  css  js  c++  java
  • Spring 注解 @Resource和@Autowired(转)

    鸣谢:http://my.oschina.net/u/216467/blog/205951

    @Resource和@Autowired两者都是做bean的注入使用。

    其实@Resource并不是Spring的注解,他的包是javax.annotation.Resource 需要导入。但是Spring支持该注解的注入。

    共同点:两者都可以写在字段和setter方法上。两者如果都写在字段上,就不需要写写setter方法。

    不同点如下:

    先来说一说@Autowired

        @Autowired为Spring提供的注解,

        需导入Package:org.springframework.beans.factory.annotation.Autowired;

        只按照byType 注入。

    @Autowired 
    private UserDao  userDao;//用于字段上
    @Autowired
    public void setUserDao(UserDao userDao) {//用于属性的setter方法上
         this.userDao= userDao;
    }

    @Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false。如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:

    @Autowired  @Qualifier("userDao")
    private PersonDao  personDao;

    再说说@Resource

    首先通过eclipe查看其官方解释:


    The Resource annotation marks a resource that is needed by the application. This annotation may be applied to an application component class, or to fields or methods of the component class. When the annotation is applied to a field or method, the container will inject an instance of the requested resource into the application component when the component is initialized. If the annotation is applied to the component class, the annotation declares a resource that the application will look up at runtime.

    --资源注释标识应用程序所需要的资源。此注释可应用于应用组件类,或用于组件类的字段或方法。当将注释应用于某个字段或方法时,容器将在该组件初始化时向应用程序组件注入所需资源的实例。如果将注释应用于组件类,则该注释声明该应用程序将在运行时查找该资源。

    @Resource默认按 byName 自动注入,由J2EE提供。

        需导入Package:  javax.annotation.Resource

        @Resource有两个中重要的属性:name和type ,而Spring将@Resource注解的name属性解析为bean的

        名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用

        type属性时则使用 byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

    @Resource(name=“userDao”)
    private UserDao  userDao;//用于字段上
    @Resource(name=“userDao”)
    public void setUserDao(UserDao userDao) {//用于属性的setter方法上
         this.userDao= userDao;
    }

        注:最好是将@Resource放在setter方法上。

        @Resource装配顺序 

      (1). 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常;

      (2). 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常;

      (3). 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常;

      (4). 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

        @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入。

  • 相关阅读:
    识别IE11浏览器
    国庆过后老革命
    有些东西再忙也要做
    云计算
    SVN下Update出现代码文件删除状态问题
    如何避免历史回退到登录页面
    CodeSmith连Oracle
    NHibernate直接执行SQL进行插入
    nhibernate实体类主键ID赋值问题
    NHibernate不支持复杂的linq,就一定要用DataTable这么低级吗
  • 原文地址:https://www.cnblogs.com/wql025/p/4806950.html
Copyright © 2011-2022 走看看