经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
@ComponentScan注解用法之包路径占位符解析
来源:jb51  时间:2021/8/16 16:35:00  对本文有异议

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

答案是肯定的。

代码测试

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

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

  1. basepackages=com.xxx.fame.placeholder

编写一个Bean,空类即可。

  1. package com.xxx.fame.placeholder;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class ComponentBean {
  5. }

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

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

  1. package com.xxx.fame.placeholder;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.PropertySource;
  5. @PropertySource("classpath:componentscan.properties")
  6. @ComponentScan("${basepackages}")
  7. public class ComponentScanPlaceholderDemo {
  8. public static void main(String[] args) {
  9. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  10. context.register(ComponentScanPlaceholderDemo.class);
  11. context.refresh();
  12. ComponentBean componentBean = context.getBean(ComponentBean.class);
  13. System.out.println(componentBean);
  14. }
  15. }

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

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

  1. @Component
  2. @PropertySource("classpath:componentscan.properties")
  3. 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}”。

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

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

  1. // ConfigurationClassParser#doProcessConfigurationClass
  2. protected final SourceClass doProcessConfigurationClass(
  3. ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
  4. throws IOException {
  5. // 扫描到的 配置类是否添加了@Component注解,如果外部类添加了@Component注解,再处理内部类
  6. if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
  7. // Recursively process any member (nested) classes first
  8. processMemberClasses(configClass, sourceClass, filter);
  9. }
  10. // 处理所有的@PropertySource注解,由于@PropertySource被JDK1.8中的元注解@Repeatable所标注
  11. // 因此可以在一个类中添加多个
  12. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  13. sourceClass.getMetadata(), PropertySources.class,
  14. org.springframework.context.annotation.PropertySource.class)) {
  15. if (this.environment instanceof ConfigurableEnvironment) {
  16. processPropertySource(propertySource);
  17. } else {
  18. logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
  19. "]. Reason: Environment must implement ConfigurableEnvironment");
  20. }
  21. }
  22. // 处理所有的@ComponentScan注解,@ComponentScan注解也被@Repeatable注解所标注
  23. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
  24. sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  25. if (!componentScans.isEmpty() &&
  26. !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  27. for (AnnotationAttributes componentScan : componentScans) {
  28. // The config class is annotated with @ComponentScan -> perform the scan immediately
  29. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  30. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  31. // Check the set of scanned definitions for any further config classes and parse recursively if needed
  32. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  33. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  34. if (bdCand == null) {
  35. bdCand = holder.getBeanDefinition();
  36. }
  37. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  38. parse(bdCand.getBeanClassName(), holder.getBeanName());
  39. }
  40. }
  41. }
  42. }
  43. // 删除其它与本次分析无关的代码....
  44. // No superclass -> processing is complete
  45. return null;
  46. }

底层行为分析

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

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

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

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

  1. // ConfigurationClassParser#doProcessConfigurationClass
  2. protected final SourceClass doProcessConfigurationClass(
  3. ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
  4. throws IOException {
  5. // 扫描到的 配置类是否添加了@Component注解,如果外部类添加了@Component注解,再处理内部类
  6. if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
  7. // Recursively process any member (nested) classes first
  8. processMemberClasses(configClass, sourceClass, filter);
  9. }
  10. // 处理所有的@PropertySource注解,由于@PropertySource被JDK1.8中的元注解@Repeatable所标注
  11. // 因此可以在一个类中添加多个
  12. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  13. sourceClass.getMetadata(), PropertySources.class,
  14. org.springframework.context.annotation.PropertySource.class)) {
  15. if (this.environment instanceof ConfigurableEnvironment) {
  16. processPropertySource(propertySource);
  17. } else {
  18. logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
  19. "]. Reason: Environment must implement ConfigurableEnvironment");
  20. }
  21. }
  22. // 处理所有的@ComponentScan注解,@ComponentScan注解也被@Repeatable注解所标注
  23. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
  24. sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  25. if (!componentScans.isEmpty() &&
  26. !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  27. for (AnnotationAttributes componentScan : componentScans) {
  28. // The config class is annotated with @ComponentScan -> perform the scan immediately
  29. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  30. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  31. // Check the set of scanned definitions for any further config classes and parse recursively if needed
  32. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  33. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  34. if (bdCand == null) {
  35. bdCand = holder.getBeanDefinition();
  36. }
  37. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  38. parse(bdCand.getBeanClassName(), holder.getBeanName());
  39. }
  40. }
  41. }
  42. }
  43. // 删除其它与本次分析无关的代码....
  44. // No superclass -> processing is complete
  45. return null;
  46. }

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

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

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

  1. package com.xxx.fame.placeholder;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. import org.springframework.context.annotation.ComponentScan;
  4. @ComponentScan("${basepackages}")
  5. public class ComponentScanPlaceholderDemo {
  6. public static void main(String[] args) {
  7. // 手动调用System#setProperty方法,设置 “basepackages”及其属性值。
  8. System.setProperty("basepackages","com.xxx.fame");
  9. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  10. context.register(ComponentScanPlaceholderDemo.class);
  11. context.refresh();
  12. ComponentBean componentBean = context.getBean(ComponentBean.class);
  13. System.out.println(componentBean);
  14. }
  15. }

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

  1. @ComponentScan("${basepackages}")
  2. @PropertySource("classpath:componentscan.properties")
  3. public class ComponentScanPlaceholderDemo {
  4. public static void main(String[] args) {
  5. System.setProperty("basepackages","com.xxx.fame");
  6. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  7. context.register(ComponentScanPlaceholderDemo.class);
  8. context.refresh();
  9. String value = context.getEnvironment().resolvePlaceholders("${basepackages}");
  10. System.out.println("${basepackages}占位符的值究竟是 com.xxx.fame 还是 com.unknow 呢? " + value);
  11. }
  12. }
  1. #在componentscan.properties指定相同的属性名,但值不同
  2. basepackages=com.unknow

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

可以看到是通过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方法。

  1. // ComponentScanAnnotationParser#parse
  2. public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
  3. ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
  4. componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
  5. // 删除与本次分析无关的代码.....
  6. Set<String> basePackages = new LinkedHashSet<>();
  7. String[] basePackagesArray = componentScan.getStringArray("basePackages");
  8. for (String pkg : basePackagesArray) {
  9. String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
  10. ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
  11. Collections.addAll(basePackages, tokenized);
  12. }
  13. // 删除与本次分析无关的代码.....
  14. return scanner.doScan(StringUtils.toStringArray(basePackages));
  15. }

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

  1. // ClassPathBeanDefinitionScanner#doScan
  2. protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
  3. Assert.notEmpty(basePackages, "At least one base package must be specified");
  4. Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
  5. for (String basePackage : basePackages) {
  6. Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
  7. // ...省略其它代码
  8. }
  9. return beanDefinitions;
  10. }

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

  1. // ClassPathScanningCandidateComponentProvider#findCandidateComponents
  2. public Set<BeanDefinition> findCandidateComponents(String basePackage) {
  3. if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
  4. return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
  5. } else {
  6. return scanCandidateComponents(basePackage);
  7. }
  8. }

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

  1. // ClassPathScanningCandidateComponentProvider#DEFAULT_RESOURCE_PATTERN
  2. static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
  3. //ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX
  4. String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
  5. // ClassPathScanningCandidateComponentProvider#scanCandidateComponents
  6. private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
  7. Set<BeanDefinition> candidates = new LinkedHashSet<>();
  8. try {
  9. String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
  10. resolveBasePackage(basePackage) + '/' + this.resourcePattern;
  11. // 删除与本次分析无关的代码......
  12. } catch (IOException ex) {
  13. throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
  14. }
  15. return candidates;
  16. }

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

  1. // ClassPathScanningCandidateComponentProvider#resolveBasePackage
  2. protected String resolveBasePackage(String basePackage) {
  3. return ClassUtils.convertClassNameToResourcePath(getEnvironment().resolveRequiredPlaceholders(basePackage));
  4. }

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

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

  1. // AbstractEnvironment#resolvePlaceholders
  2. public String resolvePlaceholders(String text) {
  3. return this.propertyResolver.resolvePlaceholders(text);
  4. }
  5. // AbstractEnvironment#resolveRequiredPlaceholders
  6. public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
  7. return this.propertyResolver.resolveRequiredPlaceholders(text);
  8. }

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

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

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

  1. @Nullable
  2. private PropertyPlaceholderHelper nonStrictHelper;
  3. @Nullable
  4. private PropertyPlaceholderHelper strictHelper;
  5. // AbstractPropertyResolver#resolvePlaceholders
  6. public String resolvePlaceholders(String text) {
  7. if (this.nonStrictHelper == null) {
  8. this.nonStrictHelper = createPlaceholderHelper(true);
  9. }
  10. return doResolvePlaceholders(text, this.nonStrictHelper);
  11. }
  12. // AbstractPropertyResolver#resolveRequiredPlaceholders
  13. public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
  14. if (this.strictHelper == null) {
  15. this.strictHelper = createPlaceholderHelper(false);
  16. }
  17. return doResolvePlaceholders(text, this.strictHelper);
  18. }

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

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

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

  1. // PropertyPlaceholderHelper#parseStringValue
  2. protected String parseStringValue(
  3. String value, PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {
  4. // 省略与本次分析无关代码......
  5. StringBuilder result = new StringBuilder(value);
  6. while (startIndex != -1) {
  7. int endIndex = findPlaceholderEndIndex(result, startIndex);
  8. if (endIndex != -1) {
  9. // 省略与本次分析无关代码......
  10. } else if (this.ignoreUnresolvablePlaceholders) {
  11. // Proceed with unprocessed value.
  12. startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
  13. } else {
  14. throw new IllegalArgumentException("Could not resolve placeholder '" +
  15. placeholder + "'" + " in value \"" + value + "\"");
  16. }
  17. visitedPlaceholders.remove(originalPlaceholder);
  18. } else {
  19. startIndex = -1;
  20. }
  21. }
  22. return result.toString();
  23. }

总结

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

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

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号