【问题标题】:How to inject an interface that inherits from another interface that has an implementation in Spring如何注入一个继承自另一个在 Spring 中实现的接口的接口
【发布时间】:2022-01-15 17:19:40
【问题描述】:

我的应用程序的基础设施包中有一个接口和实现。 在域层中,我想使用从基础设施接口继承的另一个接口来访问这个接口。但是Spring无法识别该接口对应的bean

基础设施包


    interface PushNotificationService {
       fun push(): Mono<Void>
    }
    
    @Service
    class PushNotificationServiceImpl() : PushNotificationService {
        override fun send(): Mono<Void> {
            //Call grpc to push notification
        }
    }

域名包


    //import PushNotificationService from the infrastructure package
    
    interface PushNotificationService: PushNotificationService
    
    @Service
    class MessengerServiceImpl(
        @Autowired val pushNotificationService: PushNotificationService //I want to use the interface defined in my domain layer
    )

有什么办法可以做这样的事情吗?

【问题讨论】:

  • 不,你不能,因为你的 PushNotificationService 没有实现!
  • 您应该将接口移动到域模块,因为域不应该依赖于基础设施。

标签: java spring spring-boot kotlin


【解决方案1】:

您可以配置注解@ComponentScan,使其从特定基础设施包中排除bean,并考虑您的域包中的bean。

这样的东西对你有用

@ComponentScan(basePackages = { "com.example.my.domain.package" },
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "com.example.my.infrastructure.package.*"))
public class Application { ...

正如 Simon Martinelli 在 cmets 中指出的那样,我希望您在您的域包中为该接口提供一个实现,否则这根本没有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 2013-10-22
    • 2020-12-09
    • 2010-12-13
    • 2013-08-12
    • 1970-01-01
    • 2012-05-12
    • 2019-08-04
    相关资源
    最近更新 更多