首页 > 解决方案 > 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 控制器TitleControllerCompanyController每个控制器都引用一个或多个服务。服务是实现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等等。

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

非常感谢。

标签: javaspringspring-data-jpa

解决方案


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

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


推荐阅读