Java 依赖注入 - 如何将 @Inject 注入到可调用对象中

Java Dependency Injection - How to @Inject into a Callable

我有一个 Struts/J2EE 申请。

我有一个 class 创建一个可调用对象。

    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 任何其他 classes,即它们是 null.这是因为可调用对象是使用 new 关键字创建的并失去了它的 DI 范围。

问题

如何创建仍然能够进行依赖注入的可调用对象?

更多信息:

这里是可调用的class(注入的TripAutoApprovalEscalationServicenull):

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);