@ComponentScan扫描多个包失效问题

使用@ComponentScan({"com.jiepuxun.bolipiuser","com.jiepuxun.bolipicommon"})注解扫描多个子目录时并不能生效

项目结构如下:

img

代码如下

package com.jiepuxun.bolipiuser;
@ComponentScan({"com.jiepuxun.bolipicommon","com.jiepuxun.bolipiuser"})
@MapperScan("com.jiepuxun.bolipidao.mapper")
@EnableCaching
@EnableMongoRepositories
@SpringBootApplication
public class BolipiUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(BolipiUserApplication.class, args);
    }

}
package com.jiepuxun.bolipicommon.mongo.repository;

@Repository
public interface MongoBlogsRepository extends MongoRepository<MongoBlogs, String> {

}

报错信息如下:

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

Description:

Field blogsRepository in com.jiepuxun.bolipiuser.service.blog.BlogService required a bean of type 'com.jiepuxun.bolipicommon.mongo.repository.MongoBlogsRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.jiepuxun.bolipicommon.mongo.repository.MongoBlogsRepository' in your configuration.

出现错误后,我改用@ComponentScans也不起作用,只有在@ComponentScan参数仅有一个的时候才会生效,但是这样就无法扫描到启动类所在包的controller类了,网上大多数答案都说使用@ComponentScan({"com.example.demo1","com.example.demo2"})格式的注解,我就是这么写的,但是并没有生效。

改成下面这种方式也不生效:
@MapperScan("com.jiepuxun.bolipidao.mapper")
@EnableCaching
@EnableMongoRepositories
@SpringBootApplication(scanBasePackages = {"com.jiepuxun.bolipicommon.mongo.repository","com.jiepuxun.bolipiuser"})

我在追踪@ComponentScan注解时发现并不是注解不生效,只是interface接口不能注入而已,因此推测是我的mongodb使用方式有错误,可能是因为此时mongo还没有实例化,只是个接口,所以无法注入。
希望大家指出我的错误

问题解决啦,@ComponentScan扫描配置没有问题,出错原因是:@ComponentScan扫描只会注入有@Component等注解的类,而不是接口,所以实际上mongo repository的接口并没有实例化注入spring容器。@EnableMongoRepository注解可以指定basePackages,所以配置一下@EnableMongoRepository就可以了。
解决后的代码如下:


@ComponentScan(basePackages = {"com.jiepuxun.bolipicommon.mongo","com.jiepuxun.bolipiuser"})
@MapperScan("com.jiepuxun.bolipidao.mapper")
@EnableCaching
@EnableMongoRepositories(basePackages = {"com.jiepuxun.bolipicommon.mongo.repository"})
@SpringBootApplication
public class BolipiUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(BolipiUserApplication.class, args);
    }

}

这个结果虽然可以实现,不过就像评论区的老哥说的,启动类越简单越好,所以后续会把注解配置往配置类转移。谢谢大家积极解答问题!

你是不是只扫描com.jiepuxun.bolipiuser包时候有效?你试一下把我启动类放到com.jiepuxun包下面,应该就可以了

启动类越简洁越好,你要做扫描,自己新建配置类,配置类加包扫描注解,不要在启动类做

我有个疑问,@SpringBootApplication不是包含@ComponentScan呢么

报错的那个类是因为你的mapper没注册上,你的mapperscan也要扫描多个包,建议不同模块的目录结构保持一致,就不会有这些问题