[英]Spring boot dependency injection of an interface
我有 2 个 spring 启动微服务让我们说核心和持久性。 其中持久性依赖于核心。
我在核心中定义了一个接口,其实现在持久性内部,如下所示:
核
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 的组件扫描中包含了 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;
}
}
As stated in the error message hint: Consider defining a bean of type 'com.mine.service.MyDaoService' in your configuration to solve this problem you can define in your package com.mine
a configuration class named MyConfiguration
annotated with @Configuration
including a名为 myDaoService 的 bean,如下所示:
@Configuration
public class MyConfiguration {
@Bean
public MyDaoService myDaoService() {
return new MyDaoServiceImpl();
}
}
尝试以下操作,将MyRestApiApplication
class 移动到com.mine
package 并删除@ComponentScan
注释。
package com.mine;
@SpringBootApplication
@EnableScheduling
public class MyRestApiApplication {
public static void main(String[] args) {
SpringApplication.run(MyRestApiApplication.class, args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.