Parameter 0 of constructor in com.xx.campaign_api.controller.MyController required a bean of type 'com.xx.campaign.common.service.MyService' that could not be found.
我们有多模块的弹簧靴3.4.2项目,以下POM:
<project xxx
<groupId>org.springframework</groupId>
<artifactId>our-service</artifactId>
<version>0.1.0</version>
<packaging>pom</packaging>
<modules>
<module>campaign-common</module>
<module>campaign-api</module>
<module>campaign-schedule</module>
</modules>
</project>
在API模块中,我们有一个像这样的REST控制器:
package com.xx.campaign_api.controller;
import com.xx.campaign.common.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private MyService testService;
@Autowired
public MyController(MyService testService) { // THIS LINE IS FAILING
this.testService = testService;
}
@GetMapping("/test")
public String test() {
return testService.test();
}
}
服务看起来像这样:
package com.xxx.campaign.common.service;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImpl implements MyService {
@Override
public String test() {
return "test3";
}
}
package com.xxx.campaign.common.service;
public interface MyService {
public String test();
}
主要班级看起来像这样:
package com.xx.campaign_api;
@SpringBootApplication
public class CampaignApiApplication {
public static void main(String[] args) {
SpringApplication.run(CampaignApiApplication.class, args);
}
}
在控制器模块的POM中,我们有:
<dependency>
<groupId>xx</groupId>
<artifactId>campaign-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
我也尝试了以下方法:
package com.xx.campaign_api.controller
@SpringBootApplication(scanBasePackages = "com.xx")
@RestController
public class GaController {
private MyService myService;
@Autowired
public GaController(MyService myService) { // THIS LINE IS FAILING
this.myService = myService;
}
但此应用不会从此错误开始:
Web application could not be started as there was no org.springframework.boot.web.servlet.server.ServletWebServerFactory bean defined in the context.
GEBA提供的解决方案如下:
package com.cc.campaign_api;
@SpringBootApplication(scanBasePackages = { "com.xx"})
public class CampaignApiApplication {
public static void main(String[] args) {
SpringApplication.run(CampaignApiApplication.class, args);
}
}