我有一个Struts / J2EE应用程序。
我有一个创建可调用对象的类。
ExecutorService executor = Executors.newFixedThreadPool(NO_THREADS);
List<Future<Long>> tripFutureList = new ArrayList<>();
for(Long tripId : tripIds) {
Callable<Long> callable = new CallableTripAutoApprovalEscalation(tripId);
Future<Long> future = executor.submit(callable);
tripFutureList.add(future);
}
for(Future<Long> future : tripFutureList) {
try {
logger.fine("Processed trip auto approval escalation for trip: "+future.get());
} catch (InterruptedException | ExecutionException e) {
logger.severe("There was an error processing trip."+ e.getMessage());
}
}
executor.shutdown();
这有效,但是我的问题是,当可调用对象需要执行其call()
方法时,可调用对象不能@Inject
任何其他类,即它们是null
。这是因为可调用对象是使用new
关键字创建的,并失去了其DI范围。
问题
我如何创建可调用对象以仍然能够进行依赖注入?
更多信息:
这里是可调用的类(注入的TripAutoApprovalEscalationService
为null
):
public class CallableTripAutoApprovalEscalation implements Callable<Long> {
public CallableTripAutoApprovalEscalation() {}
public static Logger logger = Logger.getLogger(CallableTripAutoApprovalEscalation.class.getName());
@Inject
private TripAutoApprovalEscalationService tripAutoApprovalEscalation;
private Long tripId;
public CallableTripAutoApprovalEscalation(Long tripId) {
this.tripId = tripId;
}
@Override
public Long call() throws Exception {
logger.info("Execute trip for callable: "+tripId);
return tripAutoApprovalEscalation.performEscalation(tripId);
}
}
您可以将其注入父容器并简单地传递该实例
//in your wrapping component
@Resource
private YourInjectableClass injectable;
//and then pass it as ctor arg
Callable<Long> callable = new CallableTripAutoApprovalEscalation(tripId, injectable);
Future<Long> future = executor.submit(callable);