本文主要是介绍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注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!