【发布时间】:2017-01-15 12:41:09
【问题描述】:
我目前正在开发一个 Java EE 7 Batch API 应用程序,我希望我的一个 CDI Bean 的生命周期与当前工作相关。
实际上我希望这个 bean 有一个 @JobScoped 范围(但它在 API 中不存在)。我也希望这个 bean 可以在我的任何作业类中注入。
起初,我想创建自己的 @JobScoped 范围,使用 JobScopedContext 等。但后来我想到 Batch API 有 JobContext bean,每个 bean 都有唯一的作业 ID。
所以我想知道我是否可以使用这个JobContext 来管理我的作业范围 bean 的生命周期。
例如,我希望我的 bean 成为工作范围:
@Alternative
public class JobScopedBean
{
private String m_value;
public String getValue()
{
return m_value;
}
public void setValue(String p_value)
{
m_value = p_value;
}
}
然后我将拥有此 bean 的生产者,它将返回与当前作业关联的 JobScopedBean(感谢 JobContext,每个作业都是唯一的)
public class ProducerJobScopedBean
{
@Inject
private JobContext m_jobContext;// this is the JobContext of Batch API
@Inject
private JobScopedManager m_manager;
@Produces
public JobScopedBean getObjectJobScoped() throws Exception
{
if (null == m_jobContext)
{
throw new Exception("Job Context not active");
}
return m_manager.get(m_jobContext.getExecutionId());
}
}
还有持有我JobScopedBean地图的经理:
@ApplicationScoped
public class JobScopedManager
{
private final ConcurrentMap<Long, JobScopedBean> mapObjets = new ConcurrentHashMap<Long, JobScopedBean>();
public JobScopedBean get(final long jobId)
{
JobScopedBean returnObject = mapObjets.get(jobId);
if (null == returnObject)
{
final JobScopedBean ajout = new JobScopedBean();
returnObject = mapObjets.putIfAbsent(jobId, ajout);
if (null == returnObject)
{
returnObject = ajout;
}
}
return returnObject;
}
当然,我会在每个作业结束时管理JobScopedBean 的销毁(通过JobListener 和CDI Event)。
如果我对这个解决方案有误,你能告诉我吗?
这对我来说看起来是正确的,但也许我错过了什么?
可能有更好的方法来处理这个问题?
谢谢。
【问题讨论】:
标签: java cdi batch-processing java-ee-7