spring boot启动不扫描创建bean怎么回事

说明你的spring boot启动时的application类不在io.github.gefangshuai.app及其子包下。

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描的。“Application类”是指SpringBoot项目入口类。如果Application类所在的包为:io.github.gefangshuai.app,则只会扫描io.github.gefangshuai.app包及其所有子包,如果service或dao所在包不在io.github.gefangshuai.app及其子包下,则不会被扫描。

改变这种扫描包的方式的原理很简单:用@ComponentScan注解进行指定要扫描的包以及要扫描的类。

可以用以下方式测试:

第一步:新建两个包cn.kfit ; org.kfit;

第二步:新建两个测试类;

在这里为了方便测试,我们让我们的类在启动的时候就进行执行,所以就编写两个类,实现接口CommandLineRunner,这样在启动的时候我们就可以看到打印信息了。

cn.kfit.MyCommandLineRunner1  : 

1

2

3

4

5

6

7

8

9

10

11

12

13

package cn.kfit;  

   

import org.springframework.boot.CommandLineRunner;  

   

@Configuration  

publicclass MyCommandLineRunner1 implements CommandLineRunner {  

   

    @Override  

    publicvoid run(String... args) throws Exception {  

       System.out.println("MyCommandLineRunner1.run()");  

   

    }  

}

org.kfit.MyCommandLineRunner2  : 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package org.kfit;  

   

import org.springframework.boot.CommandLineRunner;  

   

   

@Configuration  

publicclass MyCommandLineRunner2 implements CommandLineRunner {  

   

    @Override  

    publicvoid run(String... args) throws Exception {  

   

       System.out.println("MyCommandLineRunner2.run()");  

   

    }  

   

}

第三步:启动类进行注解指定;在App.java类中加入如下注解:

1

2

//可以使用:basePackageClasses={},basePackages={}  

@ComponentScan(basePackages={"cn.kfit","org.kfit"})

启动时如果看到打印信息:

则说明配置成功。

猜你喜欢

转载自blog.csdn.net/gangsijay888/article/details/81462129