当前位置: 首页 > 知识库问答 >
问题:

NosuchBeanDefinitionException:没有[重复]类型的合格bean

靳富
2023-03-14
@SpringBootApplication
public class Application extends SpringBootServletInitializer {


@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

    return application.sources(Application.class);
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);

}
@Service
public class OrderSvc extends AbstractService implements DAOService {
@RestController
public class OrderController {

@Autowired
CarSvc carSvc;

@Autowired
OrderSvc orderSvc;

我还有carsvcbean,它与ordersvc位于同一个包中,并扩展了相同的类,但它的注入没有问题

@Service
public class CarSvc extends AbstractService implements DAOService<Car> {

你知道为什么会出现这个例外吗?

共有1个答案

卜阳
2023-03-14

尝试使用接口而不是实现来autowire您的bean:

@RestController
public class OrderController {

    @Autowired
    @Qualifier("carSvc")
    DAOService carSvc;

    @Autowired
    @Qualifier("orderSvc")
    DAOService orderSvc;

}

编辑:但在此之前,您必须给您的服务命名:

@Service("carSvc")
public class CarSvc extends AbstractService implements DAOService<Car> {}

@Service("orderSvc")
public class OrderSvc extends AbstractService implements DAOService<Order> {}

这里发生的是Spring基于CarSvc,OrderSvc生成服务的代理,并实现DAOService,但不扩展CarSvc,OrderSvc。

//somthing like this
class CarSvcProxy implement DAOService {

    public Object getOrder(Long id) {

        try {

            // ...

            txManager.commit();

        } catch (Exception ex) {
            txManager.rollback();
        }
    }
}

@RestController
public class OrderController {

    //So when you do this :
    @Autowired
    CarSvc carSvc;

    //it's somehow like if you did : 
    CarSvc carSvc = new CarSvcProxy(); //carSvc != CarSvcProxy

    //But this will work :
    DAOService carSvc = new CarSvcProxy(); //because CarSvcProxy implement DAOService

}
 类似资料: