• @Autowired注解与@resource注解的区别(十分详细)


    @Autowired

    @Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired。

    @Autowired采取的策略为按照类型注入。

    public class UserService {
        @Autowired
        private UserDao userDao; 
    }
    

    如上代码所示,这样装配回去spring容器中找到类型为UserDao的类,然后将其注入进来。这样会产生一个问题,当一个类型有多个bean值的时候,会造成无法选择具体注入哪一个的情况,这个时候我们需要配合着@Qualifier使用。

    @Qualifier告诉spring具体去装配哪个对象。

    public class UserService {
        @Autowired
        @Qualifier(name="userDao1")    
        private UserDao userDao; 
    }
    

    这个时候我们就可以通过类型和名称定位到我们想注入的对象。

    @Resource

    @Resource注解由J2EE提供,需要导入包javax.annotation.Resource。

    @Resource默认按照ByName自动注入。

    public class UserService {
        @Resource  
        private UserDao userDao; 
        @Resource(name="studentDao")  
        private StudentDao studentDao; 
        @Resource(type="TeacherDao")  
        private TeacherDao teacherDao; 
        @Resource(name="manDao",type="ManDao")  
        private ManDao manDao; 
    }    
    

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

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

    ③如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

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

    总结:

    Spring属于第三方的,J2EE是Java自己的东西。使用@Resource可以减少代码和Spring之间的耦合。

    两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法。

    当存在多个类型,却又没有指定的时候,会报如下的错误:

    严重: Exception sendingcontext initialized event to listener instance of classorg.springframework.web.context.ContextLoaderListenerorg.springframework.beans.factory.BeanCreationException: Error creating beanwith name 'sequenceServiceImpl': Injection of resource dependencies failed;nested exception isorg.springframework.beans.factory.NoUniqueBeanDefinitionException: Noqualifying bean of type 
    
  • 相关阅读:
    简明python教程 --C++程序员的视角(九):函数式编程、特殊类方法、测试及其他
    "听话"的品格的症状
    PHP中extract()函数的妙用
    分析源码的感悟
    JWT 多网站单点登录,放弃session
    How to use php serialize() and unserialize()
    [转]很好的文章,收藏一下
    Learning from the CakePHP source code
    Learning from the CakePHP source code
    关于PHP的一小段代码求解如下求解"%2$s"
  • 原文地址:https://www.cnblogs.com/mzdljgz/p/11699278.html
Copyright © 2020-2023  润新知