@Indexed 注解 (2)

假设Spring应用中存在一个包含META-INT/spring.components资源的a.jar,但是 b.jar 仅存在模式注解,那么使用@ComponentScan扫描这两个JAR中的package时,b.jar 中的模式注解不会被识别,请务必注意这样的问题。

举个列子说明下,能够更好的理解。

DemoA项目(使用@Indexed注解)

在这里插入图片描述

DemoB项目(不使用@Indexed注解)

在这里插入图片描述

SpringBootDemo项目
在此项目中引入DemoA.jar 和 DemoB.jar 。然后进行如下测试,测试代码如下:

配置类,扫描模式注解

@Configuration @ComponentScan(basePackages = "org.springboot.demo") public class SpringIndexedConfiguration { }

测试类:

@Test public void testIndexedAnnotation(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringIndexedConfiguration.class); System.out.println("获取DemoA Jar中【org.springboot.demo.controller.DemoAController】"); DemoAController demoAController = context.getBean(DemoAController.class); System.out.println("DemoAController = " + demoAController.getClass()); System.out.println("获取DemoB Jar中【org.springboot.demo.controller.DemoBController】"); DemoBController demoBController = context.getBean(DemoBController.class); System.out.println("DemoBController = " + demoBController.getClass()); }

结果:

beanDefinitionName = demoAController 获取DemoA Jar中【org.springboot.demo.controller.DemoAController】 DemoAController = class org.springboot.demo.controller.DemoAController 获取DemoB Jar中【org.springboot.demo.controller.DemoBController】 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springboot.demo.controller.DemoBController' available

找不到 DemoBController 。

通过这样一个简单的Demo,验证了上面提到的使用注意点。

对于这种情况,Spring 官网提示了配置相关属性,不再使用index方式启动。要是这样的话,我们完全可以不添加spring-context-indexer 依赖,这样整体就不会使用index模式了。

The index is enabled automatically when a META-INF/spring.components is found on the classpath. If an index is partially available for some libraries (or use cases) but could not be built for the whole application, you can fallback to a regular classpath arrangement (as though no index was present at all) by setting spring.index.ignore to true, either as a system property or in a spring.properties file at the root of the classpath.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwgwyz.html