首页 > 解决方案 > Spring找不到bean

问题描述

我收到以下错误:

Field delegate in package.rest.api.MyApiController required a bean of type 'package.rest.api.MyApiDelegate' that could not be found.

我尝试将注释 @ComponentScan("package.rest") 添加到主类,但没有帮助。

package package;
@SpringBootApplication
@Import(SpecificationConf.class)
//@ComponentScan("package.rest")
public class MyApp extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
package package.rest.api;

@Controller
@RequestMapping(...)
public class MyApiController implements MyApi {

    @Autowired
    @Qualifier("myService")
    private MyApiDelegate delegate;

}
package package.rest;

@Service("myService")
public class MyApiDelegateImpl implements MyApiDelegate {
...
}
package package.rest.api;

public interface MyApiDelegate {
...
}

由于应用程序上下文的错误配置或不适当的 Maven 配置文件,是否会发生该问题?我试图将类移动到同一个包,但它也没有帮助。

标签: springapplicationcontextopenapi-generator

解决方案


鉴于您正在构建 JAR 文件而不是 WAR 文件,请尝试SpringBootServletInitializer从主类中删除,如下所示:

package package;

@SpringBootApplication
@Import(SpecificationConf.class)
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

推荐阅读