首页 > 解决方案 > 接口的Spring Boot依赖注入

问题描述

我有 2 个 Spring Boot 微服务,比如说核心和持久性。其中持久性依赖于核心。

我在核心中定义了一个接口,其实现在持久性内部,如下所示:

package com.mine.service;
public interface MyDaoService {
}

持久性

package com.mine.service.impl;
@Service
public class MyDaoServiceImpl implements MyDaoService {
}

我正在尝试将 MyDaoService 注入另一个仅在核心中的服务:

package com.mine.service;
@Service
public class MyService {

private final MyDaoService myDaoService;

    public MyService(MyDaoService myDaoService) {
        this.myDaoService = myDaoService;
    }
}

在这样做时,我收到了这个奇怪的错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.mine.service.MyService required a bean of type 'com.mine.service.MyDaoService' that could not be found.


Action:

Consider defining a bean of type 'com.mine.service.MyDaoService' in your configuration.

谁能解释我为什么?

注意:我已经在 springbootapplication 的 componentsscan 中包含了 com.mine.service,如下所示

package com.mine.restpi;
@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages = "com.mine")
public class MyRestApiApplication {
public static void main(String[] args) {
        SpringApplication.run(MyRestApiApplication.class, args);
    }
}

标签: javaspringspring-bootdependency-injection

解决方案


尝试将@Service注释添加到您的 impl 类并将@Autowired注释添加到构造函数。

// Include the @Service annotation
@Service
public class MyServiceImpl implements MyService {

}

// Include the @Service annotation and @Autowired annotation on the constructor
@Service
public class MyDaoServiceImpl implements MyDaoService {

    private final MyService myService ;

    @Autowired
    public MyDaoServiceImpl(MyService myService){
       this.myService = myService;
    }
}

推荐阅读