简体   繁体   English

弹簧靴扫描并注入外部非弹簧豆

[英]spring boot scanning and injecting external non-spring beans

What does it take, or is it even possible for Spring to scan and inject non-spring annotated classes? 这需要什么,或者Spring可能扫描并注入非Spring注释的类? For example. 例如。

resource.jar resource.jar

com.project.resource.ResourceInterface
com.project.resource.StandardResource <-- concrete implementation

@Singleton <--- Standard CDI annotation
public class StandardResource implements ResourceInterface{
    @Override
    public void something(){}
}

Now let's say I have a spring boot application which depends on resource.jar . 现在,我们有一个依赖于resource.jar的spring boot应用程序。

com.project.resource.SpringApp com.project.resource.SpringApp

@SpringBootApplication(scanBasePackages = {"com.project"})
@EnableAutoConfiguration
public class SpringApp{
    ... initializer
    @Inject
    private ResourceInterface resourceService; <--- this is not found
}

Is this supposed to work out of the box? 这应该可以立即使用吗? Is this even possible? 这有可能吗? I'm using spring boot 2.0.0.RELEASE . 我正在使用Spring Boot 2.0.0.RELEASE I'm getting the following error: 我收到以下错误:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MainController': Unsatisfied dependency expressed through field 'resourceService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.project.resource.ResourceInterface' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}

Thanks 谢谢

For Spring framework @Singleton has no meaning, as such even if class is picked up by component scanning it's going to be ignored. 对于Spring框架@Singleton没有任何意义,因此即使组件扫描选择了类,也将被忽略。 In order for Spring to recognize your class you can: 为了让Spring识别您的班级,您可以:

  • Create a configuration class in com.project.resource with @Bean of 使用@Bean在com.project.resource中创建一个配置类
    ResourceInterface and instantiate it as StandardResource . ResourceInterface并将其实例化为StandardResource
  • Since you are using Spring Boot you can create Auto-configuration (which will be similar to the first option) in resource.jar. 由于您使用的是Spring Boot,因此可以在resource.jar中创建自动配置(类似于第一个选项)。 You can follow examples from creating autoconfiguration . 您可以按照创建自动配置的示例进行操作。 With this approach no changes needed in com.project.resource 使用这种方法,无需在com.project.resource中进行任何更改

After that your spring boot app will run normally 之后,您的Spring Boot应用将正常运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM