@Import 注解出自spring-context包中
package org.springframework.context.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Import { Class<?>[] value(); }
該注解主要是用作導入一個配置類(Configuration),正常我們創建一個配置文件,都是在 @SpringBootApplication 的可掃描范圍內,然后業務在使用到這個配置的時候,直接 @Autowired 注入就可以正常使用。

如上圖所示,我們在使用order的時候直接注入是沒有問題的,因為OrderConfig配置類,在啟動主類的默認掃描范圍內。
@SpringBootApplication 默認掃描范圍是,掃描當前程序啟動主類所在的包,及其當前包下的所有子包。如果需要掃描父類包中的配置,需要在啟動類上使用 @ComponentScan("com.**") 注解來指明掃描的包路徑。
如果配置類所在路徑不在主類所在包,及其子包下,如下:

這種情況下,如果直接注入UserConfig的話,程序在啟動的時候就會報錯
Field user in com.example.security.securitydemo.SecurityDemoApplication required a bean of type 'com.example.security.securitydemo.bean.User' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)
解決辦法
- 在啟動類上加 @ComponentScan("com.**") 注解,直接搞定
- 使用 @Import(UserConfig.class) 注解引入
方式一簡單粗暴,直接解決問題,但是,這種解決方式,僅僅只適合你知道該類的包名,以com開頭的,假如包名是org呢,就尷尬了,在此基礎之上,就延伸出了 @Import。
@Import 就相當於原始spring xml中使用 <import/> 標簽一樣,二者沒有差異。
