1. 程式人生 > >spring boot啟動不掃描建立bean怎麼回事

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"})

啟動時如果看到列印資訊:

則說明配置成功。