代码之家  ›  专栏  ›  技术社区  ›  RobertC

Spring中默认实现的Autowire接口

  •  1
  • RobertC  · 技术社区  · 10 月前

    我得到了一个只有一个默认实现方法的接口

    @Component
    public interface ClockInterface {
    
        default Date currentDate() {
            return new Date();
        }
    }
    

    我想通过这样的构造函数将该接口注入到一些不同的服务中

    @Service
    public class Service {
        
        private ClockInterface clock;
    
        public Service(ClockInterface clock) {
            this.clock = clock
        }
    }
    

    但在运行应用程序时,我收到了消息

    Parameter 1 of constructor in com.api.app.application.Service required a bean of type 'constructor in com.api.app.application.ClockInterface' that could not be found.

    是否有一些优雅的方法将带有所有默认实现的接口注入到服务中?

    我已尝试按如下方式标记时钟接口

    @Component
    @Primary
    public interface ClockInterface {
    
        default Date currentDate() {
            return new Date();
        }
    }
    

    但这并没有改变什么

    2 回复  |  直到 10 月前
        1
  •  1
  •   Anish B.    10 月前

    这个错误非常明显,也很容易解释。

    只有当你有一个实现该接口的类并且Spring容器中有一个bean时,带接口的字段注入才有效。

    在接口中引入默认方法无助于进行注入。

        2
  •  0
  •   RobertC    10 月前

    我刚刚为该界面添加了简单的配置

    @Configuration
    public class ClockConfig {
        @Bean
        public ClockInterface clock() {
            return new ClockInterface() {};
        }
    }