一、@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 )都可以

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;

相关文章:

  • 2020-10-09
  • 2021-04-11
  • 2022-01-24
  • 2021-10-17
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
  • 2021-07-30
  • 2021-07-31
  • 2022-12-23
相关资源
相似解决方案