简体   繁体   English

基于CDI构造函数的@Resource注入

[英]CDI constructor-based injection with @Resource

Is it possible to do a constructor-based CDI injection of a @Resource type of instance? 是否可以对@Resource类型的实例进行基于构造函数的CDI注入?

I have the following class: 我有以下课程:

class MyClass {

  @Resource
  private ManagedExecutorService executorService;

  @Inject
  private MyService myservice;

}

I would like to convert it into something like this: 我想把它转换成这样的东西:

class MyClass {

  private final ManagedExecutorService executorService;
  private final MyService myservice;

  @Inject
  MyClass(ManagedExecutorService executorService, MyService myService) 
  {
    this.executorService = executorService;
    this.myService = myService;
  }

}

This would make the class immutable and easier to unit test. 这将使类不可变并且更容易进行单元测试。 The problem is that since the executorService needs to be obtained via a @Resource annotation, it doesn't seem to be injectable via the constructor. 问题是,由于需要通过@Resource注释获取executorService,因此它似乎不能通过构造函数注入。

Here is what I ended up doing - I created a producer class to managed the resource object: 这是我最终做的 - 我创建了一个生产者类来管理资源对象:

public class ExecutorServiceProducer {

    @Resource
    private ManagedExecutorService managedExecutorService;

    @Produces
    @Managed
    public ExecutorService createManagedExecutorService() {
        return managedExecutorService;
    }

}

and I created this custom annotation: 我创建了这个自定义注释:

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Managed {
}

and then I was able to annotate my class as follows: 然后我能够按如下方式注释我的课程:

class MyClass {

  private final ExecutorService executorService;
  private final MyService myservice;

  @Inject
  MyClass(@Managed ExecutorService executorService, MyService myService) 
  {
    this.executorService = executorService;
    this.myService = myService;
  }

}

This way I can unit test the class by providing my own ExecutorService (non-container managed) instance. 这样我就可以通过提供自己的ExecutorService(非容器管理)实例来对该类进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM