在方法上使用@Async注释时来自CglibAopProxy的NPE

时间:2017-10-14 15:39:15

标签: java spring asynchronous

在尝试使用@Async注释发送电子邮件的方法时,我正在获取NPE。

@Async
@Override
public void sendCloseShiftInfoFromText(Double cashBox, Double cache, Double bankKart, Double payWithCard,
                                       Double allPrice, Collection<? extends User> users, Double shortage) {
    MimeMessagePreparator[] mimeMessages = new MimeMessagePreparator[users.size()];
    int messageNum = 0;
    for (User user : users) {
        String email = user.getEmail();
        if (email == null) {
            continue;
        }
        mimeMessages[messageNum++] = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom(properties.getMail().getSender());
            messageHelper.setTo(email);
            messageHelper.setSubject(closeShiftSubject);
            String html = htmlService.getCloseShiftFromText(closeShiftText, cashBox, cache, bankKart, payWithCard,
                    allPrice, closeShiftView, users, shortage);
            messageHelper.setText(html, true);
        };
    }
    if (messageNum == 0) {
        return;
    }
    javaMailSender.send(mimeMessages);
}

以下是我得到的例外情况:

20:24:57.565 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - 
Asynchronous Exception :Could not prepare mail; nested exception is java.lang.NullPointerException
20:24:57.565 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Method name :sendCloseShiftInfoFromText
20:24:57.565 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :121246.0
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :0.0
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :0.0
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :0.0
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :0.0
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :[com.cafe.crm.models.user.User@4727bacf]
20:24:57.566 [SimpleAsyncTaskExecutor-1] ERROR org.springframework.web - Parameter :121246.0

我试图找到NPE的来源。达到“String html = htmlService.getCloseShiftFromText...”后,将调用以下方法:

@Override
public String getCloseShiftFromText(String text, Double cashBox, Double cache, Double bankKart, Double payWithCard,
                                    Double allPrice, String view, Collection<? extends User> recipients,
                                    Double shortage) {
    List<User> usersOnShift = shiftService.getUsersOnShift();
    ...
}

List<User> usersOnShift = shiftService.getUsersOnShift();行开始,调试器转到CglibAopProxy类:

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object oldProxy = null;
        boolean setProxyContext = false;
        Class<?> targetClass = null;
        Object target = null;
        try {
            if (this.advised.exposeProxy) {
                // Make invocation available if necessary.
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }
            // May be null. Get as late as possible to minimize the time we
            // "own" the target, in case it comes from a pool...
            target = getTarget();
            if (target != null) {
                targetClass = target.getClass();
            }
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
            Object retVal;
            // Check whether we only have one InvokerInterceptor: that is,
            // no real advice, but just reflective invocation of the target.
            if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
                // We can skip creating a MethodInvocation: just invoke the target directly.
                // Note that the final invoker must be an InvokerInterceptor, so we know
                // it does nothing but a reflective operation on the target, and no hot
                // swapping or fancy proxying.
                Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                retVal = methodProxy.invoke(target, argsToUse);
            }
            else {
                // We need to create a method invocation...
                retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
            }
            retVal = processReturnType(proxy, target, method, retVal);
            return retVal;
        }
        finally {
            if (target != null) {
                releaseTarget(target);
            }
            if (setProxyContext) {
                // Restore old proxy.
                AopContext.setCurrentProxy(oldProxy);
            }
        }
    }

不管怎么说setProxyContext == false,调试器转到AopContext.setCurrentProxy(oldProxy);行,这就是NPE的来源。 以下是调试器的截图

enter image description here

没有注释,代码工作正常。

如果有人可以解释为什么最后一段代码按照它的方式工作,我真的很感激。找到解决方案也很不错。

1 个答案:

答案 0 :(得分:1)

微米。 Deinum感谢您的建议。事实证明调试器有误导性。我找到了通过打印到控制台给出异常的实际方法;这个方法是调用Spring SecurityContext。由于该方法使用@Async标记,因此它在新线程中运行,并且未对上下文进行身份验证。 解决方案是将SecurityContextHolder策略从默认的MODE_THREADLOCAL更改为MODE_INHERITABLETHREADLOCAL。