Spring原理分析--@Primary注解

2024-04-19 08:20

本文主要是介绍Spring原理分析--@Primary注解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.@Primary在实际项目中的应用

在支付的场景下,通常面临需要支持多个渠道的情况,常常将这些渠道具体的实现放入第三方代理模块中处理,接口请求参数中通常包含渠道字段,去掉其他业务字段及方法,示例如下:

public interface ThirdProxyService {default void doSomething(RequestData data) {System.out.println("default do something");}
}@Getter
@Setter
public class RequestData {// 参数中包含渠道字段private String payChnl;// 其他字段...
}@Service
public class GoogleThirdProxyServiceImpl implements ThirdProxyService {@Overridepublic void doSomething(RequestData requestData) {System.out.println("google do something");}
}@Service
public class HuaweiThirdProxyServiceImpl implements ThirdProxyService {@Overridepublic void doSomething(RequestData requestData) {System.out.println("huawei do something");}
}

在账单或订单服务中通常需要依赖三方代理类获取具体的渠道数据

@Service
public class BillService {@Autowiredprivate ThirdProxyService thirdProxyService;// do something...public void doBill(RequestData request) {thirdProxyService.doSomething(request);}
}

这种情况下启动会报错,因为容器中有多个ThirdProxyService的实现类,错误信息如下:

Field thirdProxyService in com.limin.study.spring.primary.BillService required a single bean, but 2 were found:- googleThirdProxyServiceImpl: defined in file [D:\gitee\SpringStudy\spring-study\target\classes\com\limin\study\spring\primary\GoogleThirdProxyServiceImpl.class]- huaweiThirdProxyServiceImpl: defined in file [D:\gitee\SpringStudy\spring-study\target\classes\com\limin\study\spring\primary\HuaweiThirdProxyServiceImpl.class]

但是我们在注入ThirdProxyService并不知道具体要调用哪个ThirdProxyService,我们希望根据渠道字段动态调用对应渠道的实现类,该如何做呢?

1)我们可以使用@Primary定义一个ThirdProxyService的动态代理类,这样BillService依赖注入时会注册此代理类

@Configuration
public class ThirdProxyAutoConfig {@Primary@Beanpublic ThirdProxyService thirdProxyInvocationHandler(ApplicationContext context){return (ThirdProxyService) Proxy.newProxyInstance(ThirdProxyService.class.getClassLoader(),ThirdProxyInvocationHandler.class.getInterfaces(), new ThirdProxyInvocationHandler(context));}
}

2)ThirdProxyInvocationHandler中定义具体的代理逻辑,这里是根据请求参数中的渠道名称匹配容器中的实现类的渠道名称,找到具体的实现类后,调用具体实现类的方法,例如:

public class ThirdProxyInvocationHandler implements ThirdProxyService, InvocationHandler {private ApplicationContext context;private Class delegateClass;private Map<String, IChnlSupport> serviceCache = new ConcurrentHashMap<>();public ThirdProxyInvocationHandler(ApplicationContext context){this.context = context;delegateClass = ThirdProxyService.class;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {if (args == null || args.length == 0) {return null;}// 这里从参数中获取渠道名String payChnl = getChnl(args);if (StringUtils.isEmpty(payChnl)) {return null;}// 获取具体的实现类Object service = getService(payChnl);// 调用具体实现类的方法return method.invoke(service, args);}protected String getChnl(Object[] args) {// 反射获取参数中payChnl字段值return (String) ReflectUtil.getFieldValue(args[0], "payChnl");}protected IChnlSupport getService(String payChnl) {// 先从缓存中获取IChnlSupport service = serviceCache.get(payChnl);if (service == null) {// 缓存中没有,从spring容器中获取Map<String, IChnlSupport> beanMap = context.getBeansOfType(IChnlSupport.class);if (!CollectionUtils.isEmpty(beanMap)) {// 从容器中匹配ThirdProxyService的子类,且渠道名称payChnl匹配Optional<IChnlSupport> serviceOptional = beanMap.values().stream().filter(thirdServiceImpl -> delegateClass.isAssignableFrom(thirdServiceImpl.getClass()) && payChnl.equals(thirdServiceImpl.getPayChnl())).findAny();// 如果找到了就是具体的实现类if (serviceOptional.isPresent()) {service = serviceOptional.get();serviceCache.put(payChnl, service);}}}if (service == null){System.out.println("cannot find service, payChnl = " + payChnl);}return service;}
}

3)定义IChnlSupport接口,ThirdProxyService实现类也实现IChnlSupport接口,原因是需要根据渠道名称匹配具体的实现类

public interface IChnlSupport {String getPayChnl();
}@Service
public class GoogleThirdProxyServiceImpl implements ThirdProxyService, IChnlSupport {@Overridepublic void doSomething(RequestData requestData) {System.out.println("google do something");}@Overridepublic String getPayChnl() {return "google";}
}@Service
public class HuaweiThirdProxyServiceImpl implements ThirdProxyService, IChnlSupport {@Overridepublic void doSomething(RequestData requestData) {System.out.println("huawei do something");}@Overridepublic String getPayChnl() {return "huawei";}
}

这样再次启动服务,就不会报错了,因为@Primary注解确定了BillService中注入的对象是ThirdProxyService的动态代理类

再通过接口调用doSomething方法时,就能根据传入的payChnl找到具体的实现类执行对应渠道的方法

添加控制器类

@RestController
public class BillController {@Autowiredprivate BillService billService;@GetMapping("/doBill")public void doBill(@RequestBody RequestData requestData) {billService.doBill(requestData);}
}

调用http://127.0.0.1:8080/doBill,参数为{"payChnl": "google"}时,打印google do something;参数为{"payChnl": "huawei"}时,打印huawei do something

这样就实现了动态调用不同的实现类的效果

2.@Primary原理

SpringBoot启动时,在refresh方法中会调用invokeBeanFactoryPostProcessors扩展BeanDefinition,其中会调用到ConfigurationClassPostProcessor的processConfigBeanDefinitions,processConfigBeanDefinitions中会根据不同的情况扫描要注册的bean,源码loadBeanDefinitionsForConfigurationClass如下

private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {if (trackedConditionEvaluator.shouldSkip(configClass)) {String beanName = configClass.getBeanName();if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {this.registry.removeBeanDefinition(beanName);}this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());return;}if (configClass.isImported()) {registerBeanDefinitionForImportedConfigurationClass(configClass);}for (BeanMethod beanMethod : configClass.getBeanMethods()) {// 处理@Bean方法注册loadBeanDefinitionsForBeanMethod(beanMethod);}loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}

这里我们是通过ThirdProxyAutoConfig配置类注册的,那么会调用loadBeanDefinitionsForBeanMethod,这个方法中会调用AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata)处理相关的注解

当注册ThirdProxyService这个bean添加了@Primary注解,会将这个bean对应的BeanDefinition中的属性primary设置为true,processCommonDefinitionAnnotations源码如下:

static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);if (lazy != null) {abd.setLazyInit(lazy.getBoolean("value"));}else if (abd.getMetadata() != metadata) {lazy = attributesFor(abd.getMetadata(), Lazy.class);if (lazy != null) {abd.setLazyInit(lazy.getBoolean("value"));}}// 如果方法上有Primary注解,则设置primary属性为trueif (metadata.isAnnotated(Primary.class.getName())) {abd.setPrimary(true);}AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);if (dependsOn != null) {abd.setDependsOn(dependsOn.getStringArray("value"));}AnnotationAttributes role = attributesFor(metadata, Role.class);if (role != null) {abd.setRole(role.getNumber("value").intValue());}AnnotationAttributes description = attributesFor(metadata, Description.class);if (description != null) {abd.setDescription(description.getString("value"));}
}

在依赖注入时,首先根据类型找到容器所有的候选类,源码见DefaultListableBeanFactory#doResolveDependency

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {// 省略部分代码...// 在容器中根据类型获取候选的class,matchingBeans是bean名称和类对象的集合Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);if (matchingBeans.isEmpty()) {if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);}return null;}String autowiredBeanName;Object instanceCandidate;// 如果匹配的bean有多个if (matchingBeans.size() > 1) {// 确定使用哪个候选的beanautowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);if (autowiredBeanName == null) {if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);}else {return null;}}// 获取要注入的类型instanceCandidate = matchingBeans.get(autowiredBeanName);}// 省略其他代码...// 将instanceCandidate返回
}

determineAutowireCandidate方法中首先调用determinePrimaryCandidate会判断候选的bean中有没有被@Primary修饰的类,找到了就直接返回该类

protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {Class<?> requiredType = descriptor.getDependencyType();// 首先判断有没有primaryCandidateString primaryCandidate = determinePrimaryCandidate(candidates, requiredType);if (primaryCandidate != null) {return primaryCandidate;}// 省略其他代码...
}

determinePrimaryCandidate方法中遍历每个候选bean,调用isPrimary判断有没有primaryBeanName

protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) {String primaryBeanName = null;for (Map.Entry<String, Object> entry : candidates.entrySet()) {String candidateBeanName = entry.getKey();Object beanInstance = entry.getValue();// 判断该beanDefinition中primary是否为trueif (isPrimary(candidateBeanName, beanInstance)) {if (primaryBeanName != null) {boolean candidateLocal = containsBeanDefinition(candidateBeanName);boolean primaryLocal = containsBeanDefinition(primaryBeanName);if (candidateLocal && primaryLocal) {throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),"more than one 'primary' bean found among candidates: " + candidates.keySet());}else if (candidateLocal) {primaryBeanName = candidateBeanName;}}else {primaryBeanName = candidateBeanName;}}}return primaryBeanName;
}

isPrimary中获取beanName对应的BeanDefinition对象,判断BeanDefinition中的primary是否为true

protected boolean isPrimary(String beanName, Object beanInstance) {String transformedBeanName = transformedBeanName(beanName);if (containsBeanDefinition(transformedBeanName)) {// 判断beanDefinition中primary是否为truereturn getMergedLocalBeanDefinition(transformedBeanName).isPrimary();}BeanFactory parent = getParentBeanFactory();return (parent instanceof DefaultListableBeanFactory &&((DefaultListableBeanFactory) parent).isPrimary(transformedBeanName, beanInstance));
}

至此,我们就知道了为什么在定义的bean上添加@Primary之后,即使有多个候选类Spring也会注入该bean的原因

这篇关于Spring原理分析--@Primary注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/917026

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.