gpt4 book ai didi

java - 新线程导致 ContextNotActiveException

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:51 25 4
gpt4 key购买 nike

我正在尝试在 Wicket 框架应用程序中启动一个新线程,我得到:

Exception in thread "Thread-14" org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.RequestScoped
at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:598)
at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:71)

这个新线程位于 Web 服务中,如下所示:

@GET
@Override
@Path("notificarPadres")
public String notificarPadres(@QueryParam("centroDeCostosId") Integer centroDeCostosId, @QueryParam("userNotificadorId") String userNotificadorId, @QueryParam("mensaje") final String mensaje) {
String result = GradienteConstants.STRING_TRUE;

final Set<User> destinatarios = new HashSet<User>();
List<CentroDeCostos> listCentroCostoPadres = listCentroDeCostosPadresById(String.valueOf(centroDeCostosId));
final User notificador = getUserById(userNotificadorId.toLowerCase());

for (CentroDeCostos centroCosto : listCentroCostoPadres) {
if (hasCentroDeCostoResponsable(centroCosto)) {
User responsable = getResponsableByCc(centroCosto);
createNotificacion(responsable, notificador, mensaje);
if (isUserForMail(responsable)) {
destinatarios.add(responsable);
}
}

}

sendMailNewThread(destinatarios, notificador, mensaje);

return result;
}

private void sendMailNewThread(final Set<User> destinatarios, final User notificador, final String mensaje) {

Runnable r = new Runnable() {
@Override
public void run() {
sendEMail(destinatarios, notificador, mensaje);
}
};

Thread thread = new Thread(r);
thread.start();
}

如何避免这个错误?

最佳答案

您不应该在 JavaEE 上下文中打开线程。

您应该使用 @Asynchronous

public class EmailSender {

@Resource("java:jboss/mail/Default")
private Session mailSession;

@Asynchronous
public void sendNotification(String recipient) {
// mail sending code
}
}

@Inject将其添加到您的 Controller 中。然后,您只需调用 sendNotification ,它就会在自己的线程中执行,但由应用程序服务器管理(反过来可以使用线程池、监控等)

关于java - 新线程导致 ContextNotActiveException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com