SpringBoot的自動裝配原理
阿新 • • 發佈:2021-07-22
啟動類註解
點選檢視程式碼
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
從SpringBootApplication中可以看到
接下來主要就看
點選檢視程式碼
@EnableAutoConfiguration
這個註解下面又有
點選檢視程式碼
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage //自動匯入包 @Import(AutoConfigurationImportSelector.class) //自動匯入類中的 自動匯入類選擇器 public @interface EnableAutoConfiguration { /** * Environment property that can be used to override when auto-configuration is * enabled. */ String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class<?>[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ String[] excludeName() default {}; }
自動匯入類中AutoConfigurationPackages:
點選檢視程式碼
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(AutoConfigurationPackages.Registrar.class) //自動匯入包中的註冊類 public @interface AutoConfigurationPackage { /** * Base packages that should be registered with {@link AutoConfigurationPackages}. * <p> * Use {@link #basePackageClasses} for a type-safe alternative to String-based package * names. * @return the back package names * @since 2.3.0 */ String[] basePackages() default {}; /** * Type-safe alternative to {@link #basePackages} for specifying the packages to be * registered with {@link AutoConfigurationPackages}. * <p> * Consider creating a special no-op marker class or interface in each package that * serves no purpose other than being referenced by this attribute. * @return the base package classes * @since 2.3.0 */ Class<?>[] basePackageClasses() default {}; }
自動匯入類選擇器:AutoConfigurationImportSelector
從getCandidateConfigurations中
通過進loadFactoryName 進入
FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
後面它進行了while的迴圈 是將配置資源遍歷最後生成一個porperties檔案
結論:springboot啟動的時候所有的掃描類都會自動載入 但不一定生效 必須匯入stater包 才可以生效