那些年我们遇到的坑(3)-basePackages和scanBasePackages

1.SpringBootApplication启动时会默认扫描主类当前包及子包,如果需要扫描主类当前包外的其他包或不扫描当前包下的特定包或类,可通过下列属性实现:

Class<?>[] exclude() default {};
String[] excludeName() default {};
String[] scanBasePackages() default {};
Class<?>[] scanBasePackageClasses() default {};

详细解释请见org.springframework.boot.autoconfigure.SpringBootApplication,示例如下:

@SpringBootApplication(excludeName=("com.gxfw.wx.service.UserService"), scanBasePackages=("com.gxfw"))

excludeName属性未经测试,此处权供参考

2.@EnableFeignClients注解默认也是会扫描注解所在包的当前包及子包,如果需要扫描其他包下的FeignClient,需要单独使用属性指定

String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
Class<?>[] defaultConfiguration() default {};
Class<?>[] clients() default {};

详细解释请见org.springframework.cloud.netflix.feign.EnableFeignClients,示例如下:

@EnableFeignClients(basePackages = ("com.gxfw"))

总结:@SpringBootApplicatoin是用的@ComponentScan扫描,扫描的是Component,包括@Component, @Controller, @Service, @Repository等,而@EnableFeignClients扫描的是@FeignClient,所以在指定扫描路径时要分别指定,否则会报异常:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.gxfw.bbs.feign.ArticleFeignClient' available: expected at least 1 bean which qualifies as autowire candidate. 

以及SpringBoot的启动错误:

Description:
Field articleFeignClient in com.gxfw.bbs.wx.controller.ArticleAPI required a bean of type ‘com.gxfw.bbs.feign.ArticleFeignClient’ that could not be found.
Action:
Consider defining a bean of type ‘com.gxfw.bbs.feign.ArticleFeignClient’ in your configuration.

猜你喜欢

转载自blog.csdn.net/l1h2l3/article/details/73484806