java - Spring:实现基本接口的麻烦自动装配服务
问题描述
我对 spring 实例化和 Autowires 服务的方式有点困惑。
基本上,我正在寻找解决以下阻止我的应用程序启动的问题的解决方案。
Field titleService1 in com.scorpio.spring.security.oauth2.controller.TitleController required a single bean, but 2 were found:
- genderServiceImpl: defined in file [\spring\authorities\target\classes\com\spring\security\service\GenderServiceImpl.class]
- titleServiceImpl: defined in file [\spring\authorities\target\classes\com\spring\security\service\TitleServiceImpl.class]
我有两个 Rest 控制器TitleController
,CompanyController
每个控制器都引用一个或多个服务。服务是实现BaseService<T>
TitleController.java
@RestController
@RequestMapping("/secured/title")
public class TitleController {
@Autowired
private BaseService<Title> titleService;
}
公司控制器.java
@RestController
@RequestMapping("/secured/company")
public class CompanyController {
@Autowired
private BaseService<Title> titleService;
@Autowired
private BaseService<Gender> genderService;
}
BaseService.java
public interface BaseService<T> {
T get(Integer id);
T get(String t);
List<T> getAll();
void create(T t);
T update(T t);
void delete(Integer id);
void delete(T t);
}
查看错误required a single bean, but 2 were found
,由于 有两种不同的实现BaseService
,我知道 Spring 无法确定哪个 Bean,Autowire
因为没有一个实现被注释@Qualifer
,@Primary
等等。
但更令人困惑的是,当我注释掉titleService
fromTitleController
并重新运行我的应用程序时,它就可以工作了。我的问题是 spring 如何能够自动装配适当的服务CompanyController
,为什么如果我尝试自动装配TitleController
,它不起作用?
非常感谢。
解决方案
将限定符注释与自动装配一起使用。限定符用于指定要使用的接口实现。
@Autowired
@Qualifier("Audi")
private Car car;
推荐阅读
- python - DoCPLEX:如果 2 个求解之一完成,则终止求解
- angular - 控制更改的角度反应表单集验证器
- java - 从 datetime-local html 输入插入 PSQL DB
- mysql - 无法通过 MySQL 日志的批处理脚本监控文件更改
- reactjs - 想要在反应中将用户发送到具有特定状态的另一个页面
- php - laravel 新的;应用程序已存在错误
- javascript - 不能多次调用 FileReader 事件侦听器
- typescript - 在打字稿中定义至少一个集合的属性
- matlab - Matlab将标量函数扩展为矩阵函数
- raspberry-pi - 如何更改 helm 值以保持持久性以使用某个节点上的路径