zoukankan      html  css  js  c++  java
  • spring中@Resource和@Autowired理解

    一、@Resource的理解

    @Resource在bean注入的时候使用,@Resource所属包其实不是spring,而是javax.annotation.Resource,只不过spring支持该注解
    @Resource里有name,lookup,type,authenticationType,shareable,mappedName,description这几个属性
    具体看源码结构截图

    0、可以直接在要注入的属性上这样写
    @Resource
    private User user;
    不管配置文件里有没有写id或name,都能识别到,默认应该是根据类class来识别的。

    1、name
    当spring的xml配置文件中的bean配置了name或id时,它都可以识别到,也就是如果<bean id="user_id" name="user_name" class="xxx.xxx.xxx"></bean>,那么可以在要注入的属性上加@Resource(name="user_id")或者@Resource(name="user_name")都可以

    2、lookup

    3、type
    Class type() default java.lang.Object.class;这个是源码,默认值是Object.class,那就一目了然了,无需多说了

    4、authenticationType
    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;这个是源码,AuthenticationType这是个枚举类,有两个属性CONTAINER,APPLICATION。
    暂时没搞懂这俩有啥区别,有知道的麻烦告知

    5、shareable
    指示此组件和其他组件之间是否可以共享该资源。这可以指定代表任何支持类型的连接工厂的资源,并且不能为其他类型的资源指定。它是一个布尔型,默认是true

    6、mappedName

    7、description

    当然,spring的注入不光是可以属性注入,也可以set方法和构造函数注入,也就是说
    @Resource
    public void setUser(User user) {
    this.user = user;
    }

    二、@Autowired的理解

    @Autowired是属于spring的注解,它所在的包org.springframework.beans.factory.annotation,它是按byType注入的,默认是要依赖的对象必须存在,看源码就可以理解,boolean required() default true;可以看到默认值是true,如果需要允许依赖对象是null,那就@Autowired(required=false)就可以了。

    如果我们想@Autowired按名称装配,可以结合@Qualifier注解一起使用
    @Autowired
    @Qualifier("user")
    private User user;

  • 相关阅读:
    Matlab中使用Java api画图图形并保存为jpeg格式
    基于注解的Mybatis mapper 接口注意事项
    Chap 2 Representing and Manipulating Information (CS:APP)
    设计模式之享元模式
    辛星浅析Linux中的postfix
    ZOJ 1364 Machine Schedule(二分图最大匹配)
    Scrapy系列教程(3)------Spider(爬虫核心,定义链接关系和网页信息抽取)
    恩布企业 IM iOS端 1.1 公布, 开源手机 IM
    leetcode_Power of Two_easy
    小强的HTML5移动开发之路(45)——汇率计算器【1】
  • 原文地址:https://www.cnblogs.com/shamo89/p/6939545.html
Copyright © 2011-2022 走看看