Reputation: 119
I have an interface Shape
public interface Shape {
String draw();
}
And two implementations for the above Shape interface
@Component("triangle")
public class Triangle implements Shape {
public String draw() {
return "drawing Triangle";
}
}
and
@Component("circle")
public class Circle implements Shape {
public String draw() {
return "Drawing Circle";
}
}
In my client code if I have to decide which Shape class to use at run time based on Qualifier
@Autowired
private Shape shape;
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/shape")
public String getShape(@PathParam("type")
String type) {
String a = shape.draw();
return a;
}
How to do it? I want to pass "type" which I get as a pathparam to decide which Shape object to be injected at run time. Please help me in resolving this issue.
Upvotes: 2
Views: 3442
Reputation: 119
I could figure out one way of getting around this by injecting ApplicationContext in the client code.
@Autowired
private ApplicationContext appContext;
And looking up for the bean with the help of getBean method:
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/shape/{type}")
public String getShape(@PathParam("type")
String type) {
Shape shape = appContext.getBean(type, Shape.class);
return shape.draw();
}
I hope this would help someone :)
Upvotes: 4