gpt4 book ai didi

java - 在 Spring Boot 中为接口(interface)使用 @Autowired 注解

转载 作者:行者123 更新时间:2023-11-30 10:06:39 26 4
gpt4 key购买 nike

我有一个接口(interface)(QBuilder)并且有两个类(MBuilder、TBuilder)实现了这个接口(interface)。该接口(interface)包含一个测试方法。该方法接收参数类型为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 根据参数类型重定向到我。但是在 Autowiring 的 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

Spring-boot Configuration Class.

@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 语句注入(inject)两个 bean。如下图。

RestController Class.

@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);
}
}

Note :- Here You Used generics Typed parameters which resolve at Compile Time Only. Here TCubeInfo and MCubeInfo both are different classes (they are not in relationship heirarchy). So, It is impossible to cast the object which not comes under heirarchy. It will raise ClassCastException.

关于java - 在 Spring Boot 中为接口(interface)使用 @Autowired 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54547114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com