Spring Boot + 方法攔截器

本篇說明實作方法攔截器,可針對被呼叫的服務接口進行處理

1.實作MethodInterceptor

package com.liongogo.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class ShihGoGoMethodInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("開始 ShihGoGoMethodInterceptor");
        Object ret = methodInvocation.proceed();
        System.out.println("結束 ShihGoGoMethodInterceptor");
        return ret;
    }
}

2.增加設定

package com.liongogo.configuration;

import com.liongogo.interceptor.ShihGoGoMethodInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShihGoGoMethodInterceptorConfig{
    @Bean
    public DefaultPointcutAdvisor shihGoGoMethodInterceptor(){
        ShihGoGoMethodInterceptor interceptor = new ShihGoGoMethodInterceptor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com.liongogo.controller..*.*(..))");
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}