首页 文章

创建自动配置 spring 库以弹出启动应用程序

提问于
浏览
1

我正在创建一个使用spring 4.3.0的库 . 其中一个spring-boot应用程序将使用这个库 . 目前我在spring-boot应用程序的主类中使用@ComponentScan来扫描库中的bean而不是我想自动配置它 . 所以我做的是我在库中创建了一个配置类并在配置中声明了@ComponentScan文件 .

在spring-boot应用程序中使用库后,它不扫描库中的bean并抛出,

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sample.book.client.service.BookService] found for dependency [com.sample.book.client.service.BookService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
... 33 common frames omitted

如何解决此错误?为什么Spring在@Configuration之前扫描@service类?

您的帮助应该很明显,如果需要我会提供代码示例 .

3 回答

  • 2

    我猜你的启动应用程序默认不加载你的配置 . 我猜你还没有添加

    @EnableAutoConfiguration
    

    到您的启动应用程序 .

    因此,您可以尝试将配置添加到要由应用程序加载的Annotation @EnableAutoConfiguration . 然后自动加载您在库-JAR中放入META-INF/spring.factories的配置 .

    或者您可以在 @SpringBootApplication 类中使用 @Import 配置

  • 1

    在我看来,最可能的原因是您的库驻留在与Spring启动应用程序(及其子包)不同的包中 . 使用@SpringBootApplication注释类时,还会将@ComponentScan注释设置为其默认值(即扫描给定类所在的包中的组件) .

    就个人而言,我更喜欢在我的库项目中创建一个@Configuration注释类 . 这样的类负责正确的库设置(声明组件扫描等) . 稍后,在依赖项目中,我使用@Import批注来导入该配置类(以及相应的bean) .

  • 0
    @Import({MailServiceConfig.class, ServiceConfig.class})
    

    可用于启用特定配置;

    http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html

相关问题