我正在将Weld用于CDI。我正在寻找一种运行包含已注入的bean的定期线程的方法。
主要是我想创建:
executorService.scheduleWithFixedDelay(new ExampleThread(), 1, 1, TimeUnit.SECONDS);
其中ExampleThread是:
@ApplicationScoped
public class ExampleThread implements Runnable {
@Inject
private SomeBean someBean;
public ExampleThread() {}
@Override
public void run() {
someBean.do();
}
}
问题是,一旦我使用new()创建ExampleThread,它将使它的内部bean无法使用。有没有办法以一种可行的方式创建ExampleThread?
您可以通过其构造函数将CDI bean的引用传递给可运行对象。像这样的东西:
@ApplicationScoped
public class Foo
{
@Inject
private SomeBean someBean;
// ...
public void someMethod()
{
// ...
executorService.scheduleWithFixedDelay(new ExampleThread(someBean), 1, 1, TimeUnit.SECONDS);
}
}
public class ExampleThread implements Runnable
{
private SomeBean someBean;
public ExampleThread(SomeBean someBean)
{
this.someBean = someBean;
}
@Override
public void run() {
someBean.do();
}
}
仅注入提供程序,而不使用new:
@Inject
private Provider<ExampleThread> exampleThreadProvider;
...
ExampleThread myNewExampleThreadWithWorkingInjection = exampleThreadProvider.get();