接上一篇,RocketMQ采用的是分布式的架构,其可用性非常高,相比于其他的MQ,她诞生于阿里,为了配合阿里的业务,它并没有按照JMS的规范去开发,它用Java编写,且面向过程,那先了解一下JMS的情况在项目搭建完之后启动项目就报异常,有个Service注入失败,找不到,理了好久终于发现了问题出在哪里,这是涉及到包扫描
@ComponentScan以及@MapperScan
的问题,项目是SpringBoot多模块构建,异常信息如下
...

2019-09-12 13:16:57.901  WARN 4916 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'articleController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pixel.article.service.IArticleService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
2019-09-12 13:16:57.905  INFO 4916 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-09-12 13:16:57.924  INFO 4916 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-12 13:16:58.029 ERROR 4916 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean of type 'com.pixel.article.service.IArticleService' that could not be found.


Action:

Consider defining a bean of type 'com.pixel.article.service.IArticleService' in your configuration.


Process finished with exit code 1

首先报了这个启动异常,先去看看IArticleService实现类是都有加@Service注解,如果没有加也会报bean找不到的异常,这里我发现我的实现类是加了@Service的,那再看看引用的Mapper有没有加@Mapper注解,也有,这就很奇怪了,明明都用注解标明了,怎么还是会报bean找不到呢?打开我的启动类,加上@ComponentScan(basePackages = "com.pixel.article")又好了,但是我看到别人的项目不加这个也是好的啊,只加了@MapperScan(basePackages = {"mapper接口所在包"})就好了,就很好奇,然后再看项目结构的时候,突然发现我的启动类再com.pixel.articl.api的子模块下,而其他模块都分别在com.pixel.articl.service,com.pixel.articl.dao下,这时候就恍然大悟,不加@ComponentScan的时候,默认扫描的是启动类所在的包域名,即他扫描的是com.pixel.articl.api,而我看到的别人的项目中启动类是在

com.pixel.articl
这个级别的包下,所以别人默认扫描就可以,但我默认扫描就不行了,那么这样当然扫不到article的子包service了。
所以有两种解决方案

1

把启动类移动到com.pixel.article包下面,默认扫描com.pixel.article下的所有包,这样就不会有bean找不到的问题了。

2

在启动类上添加@ComponentScan(basePackages="扫描路径")通过自己配置扫描路径,相当于不用默认扫描路径,指定更全面或所有需要单独扫描的包,支持多包扫描的。

以上,确保问题解决的流程
1.确保@Service、@Component、@Mapper等注解都配置上了
2.确保扫描包都可以扫描的到
如果报null那可能是你没有加注入注解,请查看自己的对应类是否被@Resource、@Autowried或者构造器注入以及Lombok注入