如何为动态指定的类型创建bean的新实例?

时间:2015-04-15 18:28:43

标签: java-ee cdi

我有3个班级:

class Base {...}
class Derived1 extends Base {...}
class Derived1 extends Base {...}

我想提供创建派生类的新实例的方法:

@Inject @New
Instance<Base> instance;
public <T extends B> T create(Class<T> clazz) {
    return instance.select(clazz).get();
}

但它不起作用。 instance能够创建注入点指定的Base类实例。

从概念上讲,我想注入Instance<? extends Base>,但似乎不支持。

1 个答案:

答案 0 :(得分:0)

当然我错误地建议你使用@Inject @Any @New ......你应该使用@Inject @Any

我在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();
    }
}

<强>结果: DefaultHelloService: Hello World!OtherHelloService: Hello World!