Spring:记录一个自动注入bean找不到的问题

发布于 2021-12-27  1810 次阅读


springboot的启动类注解@SpringBootApplication有一个scanBasePackages属性,用于配置扫描的包。

而@springBootApplication的默认扫描范围只是在启动类(即被@springbootApplication注解的类)所在的包及其子包,如果要使用同父maven的其他微服务项目中的bean,就需要引用配置 scanBasePackages 属性。这个和maven中导入组件直接使用不同的是需要spring去管理bean,而不是直接使用包。

注意:自定义了@SpringBootApplication的scanBasePackages属性后不会走默认扫描主类当前包及子包的逻辑,而是认定只扫描自定义配置的包路径,所以如果自定义了包路径,如果还要使用本模块的包,需要手动配置上本模块的包路径。

配置示例:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.tz.invoice", "com.tz.common.**"
        , "com.tz.file.**", "com.tz.user.**", "com.tz.message.**","com.tz.base.**"})

@SpringBootApplication 注解源码:

public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	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
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};

	/**
	 * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
	 * for a type-safe alternative to String-based package names.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	/**
	 * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 * <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 base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

欢迎欢迎~热烈欢迎~