Reputation: 410
I have an interface(QBuilder) and there are two classes(MBuilder, TBuilder) implementing this interface. The interface contains a test method. This method receives parameter type of MCubeInfo in MBuilder and TCubeInfo in TBuilder.
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";
}
}
I am expecting that when I call test method in QuerySvc, qBuilder redirect to me according to the parameter type. However in autowired QBuilder set automatically with MBuilder. Therefore when I sent TCubeInfo object to the test function, occurs an error that it can not be convert 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);
}
}
When I search the problem, I encountered with @Qualifier annotation but I cannot adapt it to my problem.
Upvotes: 2
Views: 857
Reputation: 6876
I think you should make two different beans of these two Service/Component Class that you defined.
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();
}
Now, In Your RestController
try to inject two beans with different @Qualifier
statement. As shown below.
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
andMCubeInfo
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 raiseClassCastException
.
Upvotes: 1