5

spring 方法拦截器从service层的方法上获取事务注解为什么是null

 3 years ago
source link: https://www.oschina.net/question/2507499_2320630
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

spring 方法拦截器从service层的方法上获取事务注解为什么是null

颖辉小居 发布于 12/25 14:41
阅读 142

网上很多文档说:

Transactional tx = invocation.getMethod().getAnnotation(Transactional.class);

获取的注解tx=null;

解决办法是

Method realMethod = invocation.getThis().getClass().getDeclaredMethod(invocation.getMethod().getName(),invocation.getMethod().getParameterTypes());//        Transactional tx1 = realMethod.getAnnotation(Transactional.class);//tx1 = null

但是我实践的结果是相反的,请问为什么呢?

下面是我的代码

package com.yh.consumerfinance.pmc.omc.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: Description
 * @Author: 张颖辉(yh)
 * @CreateDate: 2020/12/25 13:51
 * @UpdateUser: 张颖辉(yh)
 * @UpdateDate: 2020/12/25 13:51
 * @UpdateRemark: The modified content
 * @Version: 1.0
 */
public class ReadWriteInterceptor implements MethodInterceptor{
    

    public ReadWriteInterceptor() {
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        String methodName = invocation.getMethod().getName();
        // 下面两种方法  获取方法上的注解都是null
//        Method method = invocation.getThis().getClass().getMethod(methodName, invocation.getMethod().getParameterTypes());
//        Method realMethod = invocation.getThis().getClass().getDeclaredMethod(invocation.getMethod().getName(),invocation.getMethod().getParameterTypes());
//        Transactional tx0 = method.getAnnotation(Transactional.class); //tx0 = null
//        Transactional tx1 = realMethod.getAnnotation(Transactional.class);//tx1 = null
 // 下面 方法  获取方法上的注解不是null
        Transactional tx = invocation.getMethod().getAnnotation(Transactional.class);
        if (tx == null) {
            tx = invocation.getThis().getClass().getAnnotation(Transactional.class);
        }

        if (tx != null && tx.readOnly()) {
            //
        } else {
           //
        }

        Object var5;
        try {
            var5 = invocation.proceed();
        } catch (Throwable var9) {
            throw var9;
        } finally {
            //
        }

        return var5;
    }

}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK