java - 接口的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);
}
}
解决方案
尝试将@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;
}
}
推荐阅读
- javascript - Chrome 调试器 - 显示重复路径的“无域”部分(在 Webpack 之后)
- c# - 如何在 Xamarin 表单中创建动态单选按钮组?
- php - 使用 DOMDocument 以缩小形式保存 XML 文件
- php - 如何在 laravel 5.6 刀片中获取计数值?
- ios - Swift 4.2 - 如何在枚举函数中使用警报?
- angularjs - 执行 CORS 时自定义标头不可用
- android - Recyclerview滚动缓慢并卡住android
- ios - 在我的应用程序中点击 UITextField 时没有出现 UIKeyboard
- styles - 如何制作mapbox数字风格
- android - 使用 android 具有悬停效果的 Google geojsonlayer 多边形