Of course I've made a mistake suggesting you that you should use @Inject @Any @New
... You should use @Inject @Any
.
I've tested it on Glassfish 4.1.
HelloService.java
import javax.enterprise.context.Dependent;
@Dependent
public class HelloService {
public String getMsg() {
return "Hello World!";
}
}
DefaultHelloService.java
import javax.enterprise.context.Dependent;
@Dependent
public class DefaultHelloService extends HelloService {
public String getMsg() {
return "DefaultHelloService: Hello World!";
}
}
OtherHelloService.java
import javax.enterprise.context.Dependent;
@Dependent
public class OtherHelloService extends HelloService {
@Override
public String getMsg() {
return "OtherHelloService: " + super.getMsg();
}
}
MainServlet.java
@WebServlet(name = "demoServlet", urlPatterns = "/demo-servlet")
public class MainServlet extends HttpServlet {
@Inject @Any
Instance<HelloService> instance;
public <T extends HelloService> T create(Class<T> clazz) {
return instance.select(clazz).get();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.append(create(DefaultHelloService.class).getMsg());
writer.append(create(OtherHelloService.class).getMsg());
writer.flush();
}
}
Result:
DefaultHelloService: Hello World!OtherHelloService: Hello World!
@Inject @Any @New
. – Arek