当前位置: 首页 > news >正文

spring依赖注入详解(下)

@Autowired注解依赖注入过程

一、findAutowireCandidates()实现

  1. 找出BeanFactory中类型为type的所有的Bean的名字,注意是名字,而不是Bean对象,因为我们可以根据BeanDefinition就能判断和当前type是不是匹配,不用生成Bean对象
  2. 把resolvableDependencies中key为type的对象找出来并添加到result中
  3. 遍历根据type找出的beanName,判断当前beanName对应的Bean是不是能够被自动注入
  4. 先判断beanName对应的BeanDefinition中的autowireCandidate属性,如果为false,表示不能用来进行自动注入,如果为true则继续进行判断
  5. 判断当前type是不是泛型,如果是泛型是会把容器中所有的beanName找出来的,如果是这种情况,那么在这一步中就要获取到泛型的真正类型,然后进行匹配,如果当前beanName和当前泛型对应的真实类型匹配,那么则继续判断
  6. 如果当前DependencyDescriptor上存在@Qualifier注解,那么则要判断当前beanName上是否定义了Qualifier,并且是否和当前DependencyDescriptor上的Qualifier相等,相等则匹配
  7. 经过上述验证之后,当前beanName才能成为一个可注入的,添加到result中

二、关于依赖注入中泛型注入的实现

首先在Java反射中,有一个Type接口,表示类型,具体分类为:

  1. raw types:也就是普通Class
  2. parameterized types:对应ParameterizedType接口,泛型类型
  3. array types:对应GenericArrayType,泛型数组
  4. type variables:对应TypeVariable接口,表示类型变量,也就是所定义的泛型,比如T、K
  5. primitive types:基本类型,int、boolean
public class TypeTest<T> {private int i;private Integer it;private int[] iarray;private List list;private List<String> slist;private List<T> tlist;private T t;private T[] tarray;public static void main(String[] args) throws NoSuchFieldException {test(TypeTest.class.getDeclaredField("i"));System.out.println("=======");test(TypeTest.class.getDeclaredField("it"));System.out.println("=======");test(TypeTest.class.getDeclaredField("iarray"));System.out.println("=======");test(TypeTest.class.getDeclaredField("list"));System.out.println("=======");test(TypeTest.class.getDeclaredField("slist"));System.out.println("=======");test(TypeTest.class.getDeclaredField("tlist"));System.out.println("=======");test(TypeTest.class.getDeclaredField("t"));System.out.println("=======");test(TypeTest.class.getDeclaredField("tarray"));}public static void test(Field field) {if (field.getType().isPrimitive()) {System.out.println(field.getName() + "是基本数据类型");} else {System.out.println(field.getName() + "不是基本数据类型");}if (field.getGenericType() instanceof ParameterizedType) {System.out.println(field.getName() + "是泛型类型");} else {System.out.println(field.getName() + "不是泛型类型");}if (field.getType().isArray()) {System.out.println(field.getName() + "是普通数组");} else {System.out.println(field.getName() + "不是普通数组");}if (field.getGenericType() instanceof GenericArrayType) {System.out.println(field.getName() + "是泛型数组");} else {System.out.println(field.getName() + "不是泛型数组");}if (field.getGenericType() instanceof TypeVariable) {System.out.println(field.getName() + "是泛型变量");} else {System.out.println(field.getName() + "不是泛型变量");}}}

Spring中,但注入点是一个泛型时,也是会进行处理的,比如:

@Component
public class UserService extends BaseService<OrderService, StockService> {public void test() {System.out.println(o);}}public class BaseService<O, S> {@Autowiredprotected O o;@Autowiredprotected S s;
}
  1. Spring扫描时发现UserService是一个Bean
  2. 那就取出注入点,也就是BaseService中的两个属性o、s
  3. 接下来需要按注入点类型进行注入,但是o和s都是泛型,所以Spring需要确定o和s的具体类型。
  4. 因为当前正在创建的是UserService的Bean,所以可以通过userService.getClass().getGenericSuperclass().getTypeName()获取到具体的泛型信息,比如com.zhouyu.service.BaseService<com.zhouyu.service.OrderService, com.zhouyu.service.StockService>
  5. 然后再拿到UserService的父类BaseService的泛型变量: for (TypeVariable<? extends Class<?>> typeParameter : userService.getClass().getSuperclass().getTypeParameters()) { System._out_.println(typeParameter.getName()); }
  6. 通过上面两段代码,就能知道,o对应的具体就是OrderService,s对应的具体类型就是StockService
  7. 然后再调用oField.getGenericType()就知道当前field使用的是哪个泛型,就能知道具体类型了

三、@Primary、@Priority

1、@Primary示例

定义一个主类依赖三个bean

@Component
public class UserService {@Autowiredprivate OrderInterface orderInterface;public void test() {System.out.println(orderInterface.getClass().getSimpleName());}}public interface OrderInterface {
}@Component
public class OrderService implements OrderInterface {@Bean@Primarypublic OrderInterface order() {return new OrderService2();}
}@Component
public class OrderService1 implements OrderInterface {}public class OrderService2 implements OrderInterface {}

打印最后注入到属性的值

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);UserService userService = (UserService) applicationContext.getBean("userService");userService.test();

 打印结果:OrderService2

会对使用@Primary注解的bean注入依赖的属性或对应方法中

2、@Priority示例

@Component
public class UserService {@Autowiredprivate OrderInterface orderInterface;public void test() {System.out.println(orderInterface.getClass().getSimpleName());}}public interface OrderInterface {
}@Component
@Priority(3)
public class OrderService implements OrderInterface {}@Component
@Priority(1)
public class OrderService1 implements OrderInterface {}@Component
@Priority(4)
public class OrderService2 implements OrderInterface {}

 打印最后注入到属性的值

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);UserService userService = (UserService) applicationContext.getBean("userService");userService.test();

 打印结果:OrderService1

会对使用@Priority注解的类设置的值最小注入到对应属性或方法参数中

四、@Qualifier的使用

定义两个注解:@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier("random")
public @interface Random {
}
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier("roundRobin")
public @interface RoundRobin {
}

定义一个接口和两个实现类,表示负载均衡:

public interface LoadBalance {String select();
}
​@Component
@Random
public class RandomStrategy implements LoadBalance {@Overridepublic String select() {return null;}
}@Component
@RoundRobin
public class RoundRobinStrategy implements LoadBalance {@Overridepublic String select() {return null;}
}

使用:

@Component
public class UserService  {@Autowired@RoundRobinprivate LoadBalance loadBalance;public void test() {System.out.println(loadBalance);}}
http://www.lryc.cn/news/136622.html

相关文章:

  • python的dataframe常用处理方法
  • k8s 自身原理之高可用
  • 游乐场vr设备虚拟游乐园vr项目沉浸体验馆
  • window10安装并使用oracle
  • [Mac软件]AutoCAD 2024 for Mac(cad2024) v2024.3.61.182中文版支持M1/M2/intel
  • Oracle 主从库目录不一致(异路径)的n种处理方案及效果
  • 创建型(一) - 简单工厂模式、工厂方法模式和抽象工厂模式
  • LeetCode3.无重复字符的最长子串
  • 鲁图中大许少辉博士八一新书《乡村振兴战略下传统村落文化旅游设计》山东省图书馆典藏
  • 如何发布自己的小程序
  • 【微服务】spring 条件注解从使用到源码分析详解
  • 客户案例:高性能、大规模、高可靠的AIGC承载网络
  • Flutter性能揭秘之RepaintBoundary
  • 29.Netty源码之服务端启动:创建EventLoopSelector流程
  • Kotllin实现ArrayList的基本功能
  • C++的初步介绍,以及C++与C的区别
  • JDK 核心jar之 rt.jar
  • el-form表单验证:只在点击保存时校验(包含select、checkbox、radio)
  • Golang基本语法(上)
  • jenkins使用
  • 多线程基础篇(包教包会)
  • Android/Java中,各种数据类型之间的互相转换,给出各种实例,附上中文注释
  • 机器学习知识点总结:什么是EM(最大期望值算法)
  • 漏洞挖掘和安全审计的技巧与策略
  • [SpringBoot3]Web服务
  • 构建系统自动化-autoreconf
  • Mysql之InnoDB和MyISAM的区别
  • Unity 之 Transform.Translate 实现局部坐标系中进行平移操作的方法
  • PostgreSQL Error: sorry, too many clients already
  • Vue2(路由)