@ComponentScan注解用法之包路径占位符解析

这篇文章主要介绍了@ComponentScan注解用法之包路径占位符解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

@ComponentScan注解用法之包路径占位符解析,久久派带你了解更多相关信息。

目录
  • 代码测试
  • 底层行为分析
  • 总结

@ComponentScan注解的basePackages属性支持占位符吗?

答案是肯定的。

代码测试

首先编写一个属性配置文件(Properties),名字随意,放在resources目录下。

在该文件中只需要定义一个属性就可以,属性名随意,值必须是要扫描的包路径。

basepackages=com.xxx.fame.placeholder

编写一个Bean,空类即可。

package com.xxx.fame.placeholder;import org.springframework.stereotype.Component;@Componentpublic class ComponentBean {}

编写启动类,在启动类中通过@PropertySource注解来将外部配置文件加载到Spring应用上下文中,其次在@ComponentScan注解的value属性值中使用占位符来指定要扫描的包路径(占位符中指定的属性名必须和前面在属性文件中定义的属性名一致)。

使用Spring 应用上下文来获取前面编写的Bean,执行main方法,那么是会报错呢?还是正常返回实例呢?

package com.xxx.fame.placeholder;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.PropertySource;@PropertySource(\"classpath:componentscan.properties\")@ComponentScan(\"${basepackages}\")public class ComponentScanPlaceholderDemo {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();        context.register(ComponentScanPlaceholderDemo.class);        context.refresh();        ComponentBean componentBean = context.getBean(ComponentBean.class);        System.out.println(componentBean);    }}

运行结果如下,可以看到正常返回ComponentBean在IoC容器中的实例了。

@ComponentScan注解用法之包路径占位符解析

这里我们是将@PropertySource注解添加到启动类上,那如果将@ProperSource注解添加到ComponentBean类上,程序还可以正常运行吗(将启动类上的@PropertySource注解移除掉)?

@Component@PropertySource(\"classpath:componentscan.properties\")public class ComponentBean {}

启动应用程序。可以发现程序无法启动,抛出以下异常。在这个错误里有一个关键信息:“Could not resolve placeholder ‘basepackages\’ in value \” b a s e p a c k a g e s \” ” , 即 无 法 解 析 @ C o m p o n e n t S c a n 注 解 中 指 定 的 “ {basepackages}\””,即无法解析@ComponentScan注解中指定的“ basepackages\””,即无法解析@ComponentScan注解中指定的“{basepackages}”。

@ComponentScan注解用法之包路径占位符解析

接下来我们就分析下,为什么在启动类中添加@PropertySource注解,导入属性资源,然后在@ComponentScan注解中使用占位符就没有问题,而在非启动类中添加@PropertySource导入外部配置资源,在@ComponentScan注解中使用占位符就会抛出异常。

上面说的启动类其实也存在问题,更精准的描述应该是在调用Spring 应用上下文的refresh方法之前调用register方法时传入的Class。

// ConfigurationClassParser#doProcessConfigurationClassprotected final SourceClass doProcessConfigurationClass(			ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)			throws IOException {		// 扫描到的 配置类是否添加了@Component注解,如果外部类添加了@Component注解,再处理内部类		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {			// Recursively process any member (nested) classes first			processMemberClasses(configClass, sourceClass, filter);		}		// 处理所有的@PropertySource注解,由于@PropertySource被JDK1.8中的元注解@Repeatable所标注		// 因此可以在一个类中添加多个		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(				sourceClass.getMetadata(), PropertySources.class,				org.springframework.context.annotation.PropertySource.class)) {			if (this.environment instanceof ConfigurableEnvironment) {				processPropertySource(propertySource);			} else {				logger.info(\"Ignoring @PropertySource annotation on [\" + sourceClass.getMetadata().getClassName() +						\"]. Reason: Environment must implement ConfigurableEnvironment\");			}		}		// 处理所有的@ComponentScan注解,@ComponentScan注解也被@Repeatable注解所标注		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);		if (!componentScans.isEmpty() &&				!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {			for (AnnotationAttributes componentScan : componentScans) {				// The config class is annotated with @ComponentScan -> perform the scan immediately				Set<BeanDefinitionHolder> scannedBeanDefinitions =						this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());				// Check the set of scanned definitions for any further config classes and parse recursively if needed				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();					if (bdCand == null) {						bdCand = holder.getBeanDefinition();					}					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {						parse(bdCand.getBeanClassName(), holder.getBeanName());					}				}			}		}		// 删除其它与本次分析无关的代码....		// No superclass -> processing is complete		return null;	}

底层行为分析

要想完全搞明白这个问题,就必须清楚Spring 应用上下文关于Bean资源加载这一块以及外部资源配置方面的逻辑,由于这一块逻辑比较庞大,单篇文章很难说明白,这里就只分析产生以上错误的原因。

问题的根源就出在ConfigurationClassParser的doProcessConfigurationClass方法中,在该方法中,Spring是先处理@PropertySource注解,再处理@ComponentScan或者@ComponentScans注解,而Spring应用上下文最先处理的类是谁呢?

答案就是我们通过应用上下文的register方法注册的类。当我们在register方法注册的类上添加@PropertySource注解,那么没问题,先解析@PropertySource注解导入的外部资源,接下来再解析@ComponentScan注解中的占位符,可以获取到值。

当我们将@PropertySource注解添加到非register方法注册的类时,由于是优先解析通过register方法注册的类,再去解析@ComponentScan注解,发现需要处理占位符才能进行类路径下的资源扫描,这时候就会使用Environment对象实例去解析。结果发现没有Spring应用上下文中并没有一个名为\”basepackages\”属性,所以抛出异常。

// ConfigurationClassParser#doProcessConfigurationClassprotected final SourceClass doProcessConfigurationClass(			ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)			throws IOException {		// 扫描到的 配置类是否添加了@Component注解,如果外部类添加了@Component注解,再处理内部类		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {			// Recursively process any member (nested) classes first			processMemberClasses(configClass, sourceClass, filter);		}		// 处理所有的@PropertySource注解,由于@PropertySource被JDK1.8中的元注解@Repeatable所标注		// 因此可以在一个类中添加多个		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(				sourceClass.getMetadata(), PropertySources.class,				org.springframework.context.annotation.PropertySource.class)) {			if (this.environment instanceof ConfigurableEnvironment) {				processPropertySource(propertySource);			} else {				logger.info(\"Ignoring @PropertySource annotation on [\" + sourceClass.getMetadata().getClassName() +						\"]. Reason: Environment must implement ConfigurableEnvironment\");			}		}		// 处理所有的@ComponentScan注解,@ComponentScan注解也被@Repeatable注解所标注		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);		if (!componentScans.isEmpty() &&				!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {			for (AnnotationAttributes componentScan : componentScans) {				// The config class is annotated with @ComponentScan -> perform the scan immediately				Set<BeanDefinitionHolder> scannedBeanDefinitions =						this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());				// Check the set of scanned definitions for any further config classes and parse recursively if needed				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();					if (bdCand == null) {						bdCand = holder.getBeanDefinition();					}					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {						parse(bdCand.getBeanClassName(), holder.getBeanName());					}				}			}		}		// 删除其它与本次分析无关的代码....		// No superclass -> processing is complete		return null;	}

那么除了将@PropertySource注解添加到通过register方法注册类中(注意该方法的参数是可变参类型,即可以传递多个。如果传递多个,需要注意Spring 应用上下文解析它们的顺序,如果顺序不当也可能抛出异常),还有其它的办法吗?

答案是有的,这里先给出答案,通过-D参数来完成,或者编码(设置到系统属性中),以Idea为例,只需在VM options中添加-Dbasepackages=com.xxx.fame即可。

@ComponentScan注解用法之包路径占位符解析

或者在Spring应用上下文启动之前(refresh方法执行之前),调用System.setProperty(String,String)方法手动将属性以及属性值设置进去。

package com.xxx.fame.placeholder;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.ComponentScan;@ComponentScan(\"${basepackages}\")public class ComponentScanPlaceholderDemo {    public static void main(String[] args) {    // 手动调用System#setProperty方法,设置 “basepackages”及其属性值。        System.setProperty(\"basepackages\",\"com.xxx.fame\");        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();        context.register(ComponentScanPlaceholderDemo.class);        context.refresh();        ComponentBean componentBean = context.getBean(ComponentBean.class);        System.out.println(componentBean);    }}

而这由延伸出来一个很有意思的问题,手动调用System的setProperty方法来设置“basepackages” 属性,但同时也通过@PropertySource注解导入的外部资源中也指定相同的属性名但不同值,接下来通过Environment对象实例来解析占位符“${basepackages}”,那么究竟是哪个配置生效呢?

@ComponentScan(\"${basepackages}\")@PropertySource(\"classpath:componentscan.properties\")public class ComponentScanPlaceholderDemo {    public static void main(String[] args) {        System.setProperty(\"basepackages\",\"com.xxx.fame\");        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();        context.register(ComponentScanPlaceholderDemo.class);        context.refresh();        String value = context.getEnvironment().resolvePlaceholders(\"${basepackages}\");        System.out.println(\"${basepackages}占位符的值究竟是 com.xxx.fame 还是 com.unknow 呢? \" + value);    }}

#在componentscan.properties指定相同的属性名,但值不同basepackages=com.unknow

接下来启动应用上下文,执行结果如下:

@ComponentScan注解用法之包路径占位符解析

可以看到是通过System的setProperty方法设置的属性值生效,具体原因这里就不再展开分析了,以后会详细分析Spring中外部配置优先级问题,很有意思。

书归正传,Spring 应用上下文是如何解析占位符的呢?想要知道答案,只需要跟着ComponentScanParser的parse方法走即可,因为在Spring应用上下中是由该类来解析@ComponentScan注解并完成指定类路径下的资源扫描和加载。

其实前面已经给出了答案,就是通过Environment实例的resolvePlaceHolders方法,但这里稍有不同的是resolvePlaceholders方法对于不能解析的占位符不会抛出异常,只会原样返回,那么为什么前面抛出异常呢?答案是使用了另一个方法-resolveRequiredPalceholders方法。

在ComponentScanAnnotationParser方法中,首先创建了ClassPathBeanDefinitionScanner对象,顾名思义该类就是用来处理类路径下的BeanDefinition资源扫描的(在MyBatis和Spring整合中,MyBatis就通过继承该类来完成@MapperScan注解中指定包路径下的资源扫描)。

由于@ComponentScan注解中的basepackages方法的返回值是一个数组,因此这里使用String类型的数组来接受,遍历该数组,没有每一个获取到每一个包路径,调用Environment对象的resolvePlaceholder方法来解析可能存在的占位符。由于resolvePlaceholders方法对于不能解析的占位符不会抛出异常,因此显然问题不是出自这里(之所以要提出这一部分代码,是想告诉大家,在@ComponentScan注解中可以使用占位符的,Spring是有处理的)。

在该方法的最后调用了ClassPathBeanDefinitionScanner的doScan方法,那么我们继续往下追查,看哪里调用了Environment对象的resolveRequiredPlaceholders方法。

// ComponentScanAnnotationParser#parsepublic Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {   ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,         componentScan.getBoolean(\"useDefaultFilters\"), this.environment, this.resourceLoader);   // 删除与本次分析无关的代码.....   Set<String> basePackages = new LinkedHashSet<>();   String[] basePackagesArray = componentScan.getStringArray(\"basePackages\");   for (String pkg : basePackagesArray) {      String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);      Collections.addAll(basePackages, tokenized);   }  // 删除与本次分析无关的代码.....   return scanner.doScan(StringUtils.toStringArray(basePackages));}

在ClassPathBeanDefinitionScanner的doScan方法中,遍历传入的basePackages(即用户在@ComponentScan注解的basepackes方法中指定的资源路径,也许有小伙伴疑惑为什么我明明没有指定,只指定了其value方法,这涉及到Spring注解中的显式引用,有兴趣的小伙伴可以查看Spring 在Github项目上的Wiki),对于遍历到的每一个basepackge,都调用findCandidateComponents方法来处理,由于该方法的返回值是集合,泛型是BeanDefinitionHolder,这意味着已经根据资源路径完成了资源的扫描和加载,所以需要继续往下追查。

// ClassPathBeanDefinitionScanner#doScanprotected Set<BeanDefinitionHolder> doScan(String... basePackages) {   Assert.notEmpty(basePackages, \"At least one base package must be specified\");   Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();   for (String basePackage : basePackages) {      Set<BeanDefinition> candidates = findCandidateComponents(basePackage);      // ...省略其它代码   }   return beanDefinitions;}

ClassPathBeanDefinitionScanner并没有该方法,而是由其父类ClassPathScanningCandidateComponentProvider定义并实现。在findCandidateComponents方法中,首先判断是否使用了索引,如果使用了索引则调用addCandidateComponentsFromIndex方法,否则调用scanCandidateComponents方法(索引是Spring为了减少应用程序的启动时间,通过编译器来在编译期就确定那些类是需要IoC容器来进行管理的)。

// ClassPathScanningCandidateComponentProvider#findCandidateComponentspublic Set<BeanDefinition> findCandidateComponents(String basePackage) {   if (this.componentsIndex != null && indexSupportsIncludeFilters()) {      return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);   } else {      return scanCandidateComponents(basePackage);   }}

由于并未使用索引,所以执行scanCandidateComponents方法。在该方法中,首先创建了一个Set集合用来存放BeanDefinition,重点接下来的资源路径拼接,首先在资源路径前面拼接上“classpath*:”,然后调用resolveBasePackage方法,传入basePackage,最后拼接上“**/*.class”,看起来值的怀疑的地方只有这个resolveBasePackage方法了。

// ClassPathScanningCandidateComponentProvider#DEFAULT_RESOURCE_PATTERNstatic final String DEFAULT_RESOURCE_PATTERN = \"**/*.class\";//ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIXString CLASSPATH_ALL_URL_PREFIX = \"classpath*:\";// ClassPathScanningCandidateComponentProvider#scanCandidateComponentsprivate Set<BeanDefinition> scanCandidateComponents(String basePackage) {   Set<BeanDefinition> candidates = new LinkedHashSet<>();   try {      String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +            resolveBasePackage(basePackage) + \'/\' + this.resourcePattern;      // 删除与本次分析无关的代码......   } catch (IOException ex) {      throw new BeanDefinitionStoreException(\"I/O failure during classpath scanning\", ex);   }   return candidates;}

果不其然,在resolveBasePackage方法中,调用Environment实现类对象的resolveRequiredPlacehol-ders方法。

// ClassPathScanningCandidateComponentProvider#resolveBasePackageprotected String resolveBasePackage(String basePackage) {   return ClassUtils.convertClassNameToResourcePath(getEnvironment().resolveRequiredPlaceholders(basePackage));}

最后我们分析下为什么resolvePlaceholders方法对于不能处理的占位符只会原样返回,而resolveReq-uiredPlaceholders方法对于不能处理的占位符却会抛出异常呢?

Environment实现类并不具备占位符解析能力,其只具有存储外部配置以及查询外部配置的能力,虽然也实现了PropertyResolver接口,这也是典型的装饰者模式实现。

// AbstractEnvironment#resolvePlaceholderspublic String resolvePlaceholders(String text) {	return this.propertyResolver.resolvePlaceholders(text);}// AbstractEnvironment#resolveRequiredPlaceholderspublic String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {	return this.propertyResolver.resolveRequiredPlaceholders(text);}

@ComponentScan注解用法之包路径占位符解析

AbstractProperyResolver实现了resolvePlaceholders方法以及resolveRequiredPlaceholders方法,不过能明显看到都是委派给PropertyPlaceholderHelper类来完成占位符的解析。不过重点是在通过cr-eatePlaceholders方法创建PropertyPlaceholderHelper实例传入的布尔值。

在resolvePlaceholders方法中调用createPlaceholderHelper方法时,传入的布尔值为true,而在resolveRequiredPlaceholders方法中调用createPlaceholders方式时传入的布尔值为false。

该值决定了PropertyPlaceholderHelper在面对无法解析的占位符时的行为。

@Nullableprivate PropertyPlaceholderHelper nonStrictHelper;	@Nullableprivate PropertyPlaceholderHelper strictHelper;// AbstractPropertyResolver#resolvePlaceholderspublic String resolvePlaceholders(String text) {   if (this.nonStrictHelper == null) {      this.nonStrictHelper = createPlaceholderHelper(true);   }   return doResolvePlaceholders(text, this.nonStrictHelper);}// AbstractPropertyResolver#resolveRequiredPlaceholderspublic String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {   if (this.strictHelper == null) {      this.strictHelper = createPlaceholderHelper(false);   }   return doResolvePlaceholders(text, this.strictHelper);}

在PropertyPlaceholderHelper的parseStringValue方法中(该方法就是Spring 应用上下文中解析占位符的地方(例如@Value注解中配置的占位符))。

在该方法中,对于无法解析的占位符,首先会判断ignoreUnresolvablePlaceholders属性是否为true,如果为true,则继续尝试解析,否则(else分支)就是抛出我们前面的看到的异常。

ingnoreUresolvablePlaceholder属性的含义是代表是否需要忽略不能解析的占位符。

// PropertyPlaceholderHelper#parseStringValueprotected String parseStringValue(      String value, PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {   // 省略与本次分析无关代码......   StringBuilder result = new StringBuilder(value);   while (startIndex != -1) {      int endIndex = findPlaceholderEndIndex(result, startIndex);      if (endIndex != -1) {          // 省略与本次分析无关代码......         } else if (this.ignoreUnresolvablePlaceholders) {            // Proceed with unprocessed value.            startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());         } else {            throw new IllegalArgumentException(\"Could not resolve placeholder \'\" +                  placeholder + \"\'\" + \" in value \\\"\" + value + \"\\\"\");         }         visitedPlaceholders.remove(originalPlaceholder);      } else {         startIndex = -1;      }   }   return result.toString();}

总结

我们可以在@ComponentScan注解中通过使用占位符来外部化指定Spring 应用上下文要加载的资源路径,但需要注意的是要配合@PropertySource注解使用或者通过-D参数来指定。

在使用@PropertySource注解来导入外部配置资源的时候,需要注意的是该注解必须添加到通过调用register方法注册的配置类中,并且如果传入的是多个配置类,那么需要注意它们之间的顺序,以防因为顺序问题而导致解析占位符失败。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持趣讯吧。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/13270.html

(0)
nan
上一篇 2021-08-16
下一篇 2021-08-16

相关推荐

  • 股东代位诉讼是什么意思(股东代位权诉讼的法律条文)

    定义股东代位诉讼,又称派生诉讼、股东代表诉讼,是指当公司的合法权益受到不法侵害而公司却怠于起诉时,公司的股东代公司的位以自己的名义起诉,所获赔偿归于公司的一种诉讼形态。因此救济对象是公司权益,而非股东个人的权利和利益。前置程序股东不能直接提起代位诉

    2021-12-27
    0
  • 爱普生打印机可以扫描不能打印是怎么回事?

    爱普生打印机可以扫描不能打印是怎么回事?爱普生打印扫描一体机可以扫描文件,但是无法打印文件,该怎么解决这个问题呢?下面我们就来看看详细的教程

    2021-09-02 热点头条
    0
  • 女生同情老人买5西瓜切开发现全坏 !满满的套路啊!

    据报道,3月27日在河南驻马店,陆同学和室友在街上遇见两位大爷卖瓜,他看到二人戴着安全帽,身上衣服有点脏心生不忍,索性买了5个回去。可大跌眼镜的是,到家切开后发现,5个瓜居然全部变质。陆同学回忆,瓜是10块钱2个,大爷当时还信誓旦旦地表示包甜不熟来找他,可实际上结完账没等自己走,二人就开车走了。事后

    热点头条 2023-03-28
    0
  • 苹果手机老是跳屏怎么办(屏幕不受控制乱跳如何解决)

    摘要:手机系统问题,如果我们的苹果手机从来不关机,那么手机如果出现了屏幕偶尔乱跳的情况,那么有可能是系统问题导致的,解决的办法我们可以重启一下手机即可解决。

    2023-04-04
    0
  • 江西一对表兄妹结婚10年育1子 !丈夫向法院请求认定婚姻无效 !

    近日,江西上饶市广信区人民法院皂头法庭宣告一段存续十年的婚姻为无效婚姻,对违反公序良俗原则行为坚决说不,切实维护了人文伦理。 谢1某(谢某父亲)与谢2某(林某某母亲)系亲兄妹,原告谢某系谢1某的儿子,被告林某某系谢2某的女儿,两人恋爱后2012年开始同居,2013年6月办理结婚登记,婚后生育儿

    热点头条 2023-05-27
    0
  • 幼儿园招未成年当幼师被约谈 !官方:现已整改到位!

    近日,有网友反映,江西赣州于都罗坳镇晨光幼儿园招收还未毕业的孩子来当幼师,而且还是未成年人。为此于都县教育科技体育局:经调查,该园本学期招收了1名请假在家的初三学生马某为见习生。鉴于该园管理不到位,存在严重违反劳动法、教师无证上岗等问题,县教科体局已约谈该园园长,责令其作出深刻检查,并已下督办函,责

    热点头条 2023-04-17
    0

发表回复

登录后才能评论