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

时间:2017-02-15 11:56:13

标签: spring spring-mvc spring-boot spring-integration

我正在创建一个使用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类?

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

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

@EnableAutoConfiguration

到你的启动应用程序。

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

或者您可以在@Import班级

@SpringBootApplication进行配置

答案 2 :(得分:1)

我喜欢导入。但是我想避免在客户端代码中进行任何导入或程序包扫描。

我建立了我的库(spring-boot)

通过在资源/META-INF/spring.factories中定义配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
 com.fanniemae.ebrms.dsrunner.DecisionServiceRunnerConfiguration

在我的配置(my-lib)中添加了componentScan

@Configuration
@EnableConfigurationProperties(DecisionServiceRunnerProperties.class)
@ComponentScan(basePackages = { "com.xyz.dsrunner.*" })
public class DecisionServiceRunnerConfiguration {

并作为依赖项包含在我的客户端spring boot应用程序中。

答案 3 :(得分:0)

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

可用于启用特定配置;

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

相关问题