接口的春季启动依赖项注入



我有两个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的componentscan中包含了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;
}
}

如错误消息提示中所述:考虑在您的配置中定义类型为"com.mine.service.MyDaoService"的bean来解决此问题,您可以在包com.mine中定义一个名为MyConfiguration的配置类,该配置类用@Configuration进行注释,其中包括名为MyDaoService的bean,如下所示:

@Configuration
public class MyConfiguration {
@Bean
public MyDaoService myDaoService() {
return new MyDaoServiceImpl();
}
}

尝试以下操作,将MyRestApiApplication类移动到com.mine包中,并删除@ComponentScan注释。

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

最新更新