【问题标题】:Spring: Trouble Autowiring services implementing a base interfaceSpring:实现基本接口的麻烦自动装配服务
【发布时间】:2019-04-10 14:23:38
【问题描述】:

我对 spring 实例化和自动装配服务的方式有点困惑。

基本上,我正在寻找解决以下阻止我的应用程序启动的问题的解决方案。

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 控制器,即 TitleControllerCompanyController,每个控制器都引用一个或多个服务。服务是BaseService<T>的实现

TitleController.java

@RestController
@RequestMapping("/secured/title")
public class TitleController {

    @Autowired
    private BaseService<Title> titleService;

}

CompanyController.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 无法确定Autowire 的哪个Bean,因为没有一个实现是用@Qualifer 注释的,@ 987654332@等

但更令人困惑的是,当我从 TitleController 中注释掉 titleService 并重新运行我的应用程序时,它就可以正常工作了。我的问题是 spring 如何能够在 CompanyController 中自动装配适当的服务,为什么如果我尝试在 TitleController 中自动装配,它不起作用?

非常感谢。

【问题讨论】:

  • 你用的是什么版本的 Spring?
  • @Jay 我是5.0.2
  • 如果你通过构造函数注入而不是使用字段级别会发生什么?
  • @Jay 没有任何区别,我仍然遇到同样的错误。
  • 当你注释掉时。 CompanyController 有效吗?我的意思是 HTTP 端点。

标签: java spring spring-data-jpa


【解决方案1】:

将限定符注释与自动装配一起使用。限定符用于指定要使用的接口实现。

@Autowired
@Qualifier("Audi")
private Car car;

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多