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

相关文章

SpringBoot基础框架详解

《SpringBoot基础框架详解》SpringBoot开发目的是为了简化Spring应用的创建、运行、调试和部署等,使用SpringBoot可以不用或者只需要很少的Spring配置就可以让企业项目快... 目录SpringBoot基础 – 框架介绍1.SpringBoot介绍1.1 概述1.2 核心功能2

Spring Boot 事务详解(事务传播行为、事务属性)

《SpringBoot事务详解(事务传播行为、事务属性)》SpringBoot提供了强大的事务管理功能,通过@Transactional注解可以方便地配置事务的传播行为和属性,本文将详细介绍Spr... 目录Spring Boot 事务详解引言声明式事务管理示例编程式事务管理示例事务传播行为1. REQUI

Spring AI 实现 STDIO和SSE MCP Server的过程详解

《SpringAI实现STDIO和SSEMCPServer的过程详解》STDIO方式是基于进程间通信,MCPClient和MCPServer运行在同一主机,主要用于本地集成、命令行工具等场景... 目录Spring AI 实现 STDIO和SSE MCP Server1.新建Spring Boot项目2.a

spring security 超详细使用教程及如何接入springboot、前后端分离

《springsecurity超详细使用教程及如何接入springboot、前后端分离》SpringSecurity是一个强大且可扩展的框架,用于保护Java应用程序,尤其是基于Spring的应用... 目录1、准备工作1.1 引入依赖1.2 用户认证的配置1.3 基本的配置1.4 常用配置2、加密1. 密

Spring Boot 集成 Solr 的详细示例

《SpringBoot集成Solr的详细示例》:本文主要介绍SpringBoot集成Solr的详细示例,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录环境准备添加依赖配置 Solr 连接定义实体类编写 Repository 接口创建 Service 与 Controller示例运行

Spring Cloud GateWay搭建全过程

《SpringCloudGateWay搭建全过程》:本文主要介绍SpringCloudGateWay搭建全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录Spring Cloud GateWay搭建1.搭建注册中心1.1添加依赖1.2 配置文件及启动类1.3 测

Java如何将文件内容转换为MD5哈希值

《Java如何将文件内容转换为MD5哈希值》:本文主要介绍Java如何将文件内容转换为MD5哈希值的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java文件内容转换为MD5哈希值一个完整的Java示例代码代码解释注意事项总结Java文件内容转换为MD5

Spring Boot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)

《SpringBoot拦截器Interceptor与过滤器Filter深度解析(区别、实现与实战指南)》:本文主要介绍SpringBoot拦截器Interceptor与过滤器Filter深度解析... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实

解决Java异常报错:java.nio.channels.UnresolvedAddressException问题

《解决Java异常报错:java.nio.channels.UnresolvedAddressException问题》:本文主要介绍解决Java异常报错:java.nio.channels.Unr... 目录异常含义可能出现的场景1. 错误的 IP 地址格式2. DNS 解析失败3. 未初始化的地址对象解决

SpringBoot后端实现小程序微信登录功能实现

《SpringBoot后端实现小程序微信登录功能实现》微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程,这篇文章给大家介绍S... 目录SpringBoot实现微信小程序登录简介SpringBoot后端实现微信登录SpringBoo