java - spring boot扫描并注入(inject)外部非spring bean

标签 java spring spring-boot

这需要什么,或者 Spring 是否有可能扫描并注入(inject)非 Spring 注解的类?例如。

资源.jar

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

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

现在假设我有一个依赖于 resource.jar 的 Spring Boot 应用程序。

com.project.resource.SpringApp

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

这应该可以开箱即用吗?这可能吗?我正在使用 spring boot 2.0.0.RELEASE。我收到以下错误:

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()}

谢谢

最佳答案

对于 Spring 框架 @Singleton 没有任何意义,因此即使通过组件扫描拾取类,它也会被忽略。为了让 Spring 识别您的类(class),您可以:

  • 在 com.project.resource 中创建一个配置类,其@Bean
    ResourceInterface 并将其实例化为StandardResource
  • 由于您使用的是 Spring Boot,因此您可以在 resources.jar 中创建自动配置(与第一个选项类似)。您可以按照示例进行操作 来自creating autoconfiguration 。使用这种方法不需要更改 com.project.resource

之后您的 Spring Boot 应用程序将正常运行

关于java - spring boot扫描并注入(inject)外部非spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826905/

相关文章:

JQuery 对话框和 Datatable 一起工作

java - 使用 JPA 在另外 2 个表上通过 JOIN 从表中获取 2000 行需要更多时间

java - 无法使用内置的 BrokerService.stop 调用关闭嵌入式 activeMQ 服务

java - 在 Spring 中消耗大量 json 有效负载的最佳方法?

spring-boot - 如何设置 Spring Cloud Gateway 应用程序以便它可以使用 Spring Cloud Kubernetes 的服务发现?

java - 最新的 Java 分析器

java - com.abc.serive.MysqlService 中的字段 countRepo 需要类型为 'com.abc.repository.ClicksQuickReplyRepository' 的 bean,但无法找到

java - 调用 Fragment 的空构造函数而不是 newInstance

java - 找不到符号,接口(interface)连接

java - 为什么我获得拒绝连接到端口 338 的权限?