我有一个接口(QBuilder),有两个实现该接口的类(MBuilder,TBuilder)。该界面包含一种测试方法。此方法在MBuilder中接收MCubeInfo的参数类型,在TBuilder中接收TCubeInfo的参数类型。

public interface QBuilder<T> {

    public String test(T cubeInfo);
}

public class MBuilder implements QBuilder<MCubeInfo> {

    @Override
    public String test(MCubeInfo cubeInfo) {
        System.out.println("MCube Info");
        return "MCube";
    }
}


public class TBuilder implements QBuilder<TCubeInfo> {
        @Override
        public String test(TCubeInfo cubeInfo) {
            System.out.println("TCube Info");
            return "TCube";
        }
}


我期望当我在QuerySvc中调用测试方法时,qBuilder根据参数类型重定向到我。但是,在自动装配的QBuilder中,将使用MBuilder自动设置。因此,当我将TCubeInfo对象发送到测试函数时,发生了无法转换MCubeInfo的错误。

@RestController
public class QuerySvc {

     private QBuilder qBuilder;

     @Autowired
     public void setQBuilder(QBuilder q){
          qBuilder = q)
     }

     @RequestMapping(value = "/boot", method = RequestMethod.GET)
     public ResponseEntity<String> getTest(){

           .
           .
           .
           TCubeInfo cube = .....
           qBuilder.test(cube);

     }


}


当我搜索问题时,遇到了@Qualifier批注,但是我无法使其适应我的问题。

最佳答案

我认为您应该为您定义的这两个服务/组件类制作两个不同的bean。

public class MBuilder   //two different beans in configuration Class.
public class Tuilder



  春季启动配置类。


@Bean(name="mBuilder") //define bean name
public MBuilder mBuilder(){    //mBuilder bean for MBuilder Class.
    return new MBuilder();
}

@Bean(name="tBuilder")   //Define bean name
public TBuilder tBuilder(){   //tBuilder bean for TBuilder Class.
    return new TBuilder();
}


现在,在您的RestController中尝试注入两个具有不同@Qualifier语句的bean。如下所示。


  RestController类。


@RestController
public class QuerySvc {

     @Qualifier("tBuilder")  //Now use tBuilder Object as per Your Need.
     @Autowired
     private QBuilder tBuilder;
     @Qualifier("mBuilder") // You can use mBuilder Object as per need.
     @Autowired
     private QBuilder mBuilder;

     @Autowired
     public void setQBuilder(QBuilder q){
          qBuilder = q)
     }

     @RequestMapping(value = "/boot", method = RequestMethod.GET)
     public ResponseEntity<String> getTest(){

           .
           .
           .
           TCubeInfo cube = .....
           qBuilder.test(cube);
     }
}



  注意:-在这里,您使用了泛型类型的参数,这些参数仅在编译时解析。在这里,TCubeInfoMCubeInfo都是不同的类(它们不在关系层次结构中)。因此,不可能投射不属于层次结构的对象。它将提高ClassCastException

09-25 21:25