0

例如,我有一个在构造函数中获得依赖的类,比如

class ExampleService() {

    private Dependency dep;

    public ExampleService(Dependency dep) {
        this.dep = dep;
    }

}

和依赖类:

class Dependency {

    public static Dependency getInstance() {
        return new Dependency();
    }

    private Dependency() {
        /*constructor implementation here*/
    }

}

我想通过 @Inject EJB 注释将 Dependency.getInstance() 方法的结果注入到 ExampleService 构造函数中。可能吗?如何?谢谢你。

4

1 回答 1

0

在 CDI 中,生产者方法可以是 static,因此使用您的示例,以下内容可以正常工作:

class ExampleService() {

    private Dependency dep;

    @Inject
    public ExampleService(Dependency dep) {
        this.dep = dep;
    }

}

class Dependency {

    @Produces
    public static Dependency getInstance() {
        return new Dependency();
    }

    private Dependency() {
       /*constructor implementation here*/
    }

}

但是,就像在对您的问题的评论中提到的那样,根据您的需要,可能会有更好的方法。

于 2013-10-06T14:39:36.387 回答