最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Spring方法攔截器MethodInterceptor

 更新時間:2021年10月26日 16:47:20   作者:淡淡的倔強  
這篇文章主要介紹了使用Spring方法攔截器MethodInterceptor,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Spring方法攔截器MethodInterceptor

前言

實現(xiàn)MethodInterceptor 接口,在調(diào)用目標對象的方法時,就可以實現(xiàn)在調(diào)用方法之前、調(diào)用方法過程中、調(diào)用方法之后對其進行控制。

MethodInterceptor 接口可以實現(xiàn)MethodBeforeAdvice接口、AfterReturningAdvice接口、ThrowsAdvice接口這三個接口能夠所能夠?qū)崿F(xiàn)的功能,但是應該謹慎使用MethodInterceptor 接口,很可能因為一時的疏忽忘記最重要的MethodInvocation而造成對目標對象方法調(diào)用失效,或者不能達到預期的設想。

示例代碼如下

public class TestMethodInterceptor  {
    public static void main(String[] args) {
        ProxyFactory proxyFactory=new ProxyFactory();
        proxyFactory.setTarget(new TestMethodInterceptor());
        proxyFactory.addAdvice(new adviseMethodInterceptor());
        Object proxy = proxyFactory.getProxy();
        TestMethodInterceptor methodInterceptor = (TestMethodInterceptor) proxy;
        methodInterceptor.doSomeThing("通過代理工廠設置代理對象,攔截代理方法");
    }
    public static class adviseMethodInterceptor implements MethodInterceptor{
        @Override
        public Object invoke(MethodInvocation methodInvocation) throws Throwable {
            Object result=null;
            try{
                System.out.println("方法執(zhí)行之前:"+methodInvocation.getMethod().toString());
                result= methodInvocation.proceed();
                System.out.println("方法執(zhí)行之后:"+methodInvocation.getMethod().toString());
                System.out.println("方法正常運行結(jié)果:"+result);
                return result;
            }catch (Exception e){
                System.out.println("方法出現(xiàn)異常:"+e.toString());
                System.out.println("方法運行Exception結(jié)果:"+result);
                return result;
            }
        }
    }
    public String doSomeThing(String someThing){
        //int i=5/0;
        return "執(zhí)行被攔截的方法:"+someThing;
    }
}

正常運行結(jié)果:

方法執(zhí)行之前:public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing(java.lang.String)

方法執(zhí)行之后:public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing(java.lang.String)

方法正常運行結(jié)果:執(zhí)行被攔截的方法:通過代理工廠設置代理對象,攔截代理方法

異常運行結(jié)果:

方法執(zhí)行之前:public java.lang.String com.blog.test.aop.TestMethodInterceptor.doSomeThing(java.lang.String)

方法出現(xiàn)異常:java.lang.ArithmeticException: / by zero

方法運行Exception結(jié)果:null

Spring攔截器實現(xiàn)+后臺原理(MethodInterceptor)

MethodInterceptor

MethodInterceptor是AOP項目中的攔截器(注:不是動態(tài)代理攔截器),區(qū)別與HandlerInterceptor攔截目標時請求,它攔截的目標是方法。

實現(xiàn)MethodInterceptor攔截器大致也分為兩種:

(1)MethodInterceptor接口;

(2)利用AspectJ的注解配置;

MethodInterceptor接口

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MethodInvokeInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("before method invoke....");
        Object object = methodInvocation.proceed();
        System.out.println("after method invoke.....");
        return object;
    }
}
<!-- 攔截器 demo -->
    <bean id="methodInvokeInterceptor" class="com.paic.phssp.springtest.interceptor.method.MethodInvokeInterceptor"/>
    <aop:config>
        <!--切入點,controlller -->
        <aop:pointcut id="pointcut_test"   expression="execution(* com.paic.phssp.springtest.controller..*.*(..))" />
        <!--在該切入點使用自定義攔截器 ,按照先后順序執(zhí)行 -->
        <aop:advisor pointcut-ref="pointcut_test" advice-ref="methodInvokeInterceptor" />
    </aop:config>
    <!-- 自動掃描使用了aspectj注解的類 -->
    <aop:aspectj-autoproxy/>

執(zhí)行:

AspectJ的注解

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AutoAspectJInterceptor {
    @Around("execution (* com.paic.phssp.springtest.controller..*.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        System.out.println("AutoAspectJInterceptor begin around......");
        Object object = point.proceed();
        System.out.println("AutoAspectJInterceptor end around......");
        return object;
    }
}

運行結(jié)果:

AutoAspectJInterceptor begin around......

>>>>:isAuthenticated=false

AutoAspectJInterceptor end around......

簡單介紹下關(guān)鍵詞

  • AOP=Aspect Oriented Program面向切面(方面/剖面)編程
  • Advice(通知):把各組件中公共業(yè)務邏輯抽離出來作為一個獨立 的組件
  • Weave(織入):把抽離出來的組件(Advice),使用到需要使用該邏輯 地方的過程。
  • JoinPoint (連接點): Advice 組件可以weave的特征點。
  • PointCut(切入點):用來明確Advice需要織入的連接點
  • Aspect(切面):Aspect=Advice + PointCut

通知類型

  • @Before 在切點方法之前執(zhí)行
  • @After 在切點方法之后執(zhí)行
  • @AfterReturning 切點方法返回后執(zhí)行
  • @AfterThrowing 切點方法拋異常執(zhí)行
  • @Around環(huán)繞通知

執(zhí)行順序:

  • @Around環(huán)繞通知
  • @Before通知執(zhí)行
  • @Before通知執(zhí)行結(jié)束
  • @Around環(huán)繞通知執(zhí)行結(jié)束
  • @After后置通知執(zhí)行了!
  • @AfterReturning

切面設置

可以使用&&、||、!、三種運算符來組合切點表達式

execution表達式

"execution(public * com.xhx.springboot.controller.*.*(..))"
  • *只能匹配一級路徑
  • ..可以匹配多級,可以是包路徑,也可以匹配多個參數(shù)
  • + 只能放在類后面,表明本類及所有子類

within(類路徑) 配置指定類型的類實例,同樣可以使用匹配符

within(com.xhx.springboot..*)

@within(annotationType) 匹配帶有指定注解的類(注:與上不同)

"@within(org.springframework.stereotype.Component)"

@annotation(annotationType) 匹配帶有指定注解的方法

"@annotation(IDataSource)"

其中:IDataSource為自定義注解

import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface IDataSource {
    String value() default "dataSource";
}

下面分析下Spring @Aspect

1、注冊

org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator

看到實現(xiàn)接口BeanPostProcessor,必然在初始化Bean前后,執(zhí)行接口方法。

2、解析

AspectJAutoProxyBeanDefinitionParser.java#parse()方法

@Nullable
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
        this.extendBeanDefinition(element, parserContext);
        return null;
    }
public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(ParserContext parserContext, Element sourceElement) {
        BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext.getRegistry(), parserContext.extractSource(sourceElement));
        useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
        registerComponentIfNecessary(beanDefinition, parserContext);
    }
@Nullable
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
        return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }

3、具體實現(xiàn)

上面提到實現(xiàn)接口BeanPostProcessor,必然在初始化Bean前后,執(zhí)行接口方法??聪旅鏁r序圖:

AbstractAutoProxyCreator的postProcessAfterInitialization()方法

DefaultAopProxyFactory.createAopProxy()方法,具體創(chuàng)建代理類。兩種動態(tài)代理:JDK動態(tài)代理和CGLIB代理。

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {
            return new JdkDynamicAopProxy(config);
        } else {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");
            } else {
                return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));
            }
        }
    }

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • IntelliJ IDEA中ajax開發(fā)實現(xiàn)分頁查詢示例

    IntelliJ IDEA中ajax開發(fā)實現(xiàn)分頁查詢示例

    這篇文章主要介紹了IntelliJ IDEA中ajax開發(fā)實現(xiàn)分頁查詢,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • SpringBoot如何解決跨域Cores問題

    SpringBoot如何解決跨域Cores問題

    這篇文章主要介紹了SpringBoot如何解決跨域Cores問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-09-09
  • SpringBoot Admin健康檢查功能的實現(xiàn)

    SpringBoot Admin健康檢查功能的實現(xiàn)

    admin主要就是告訴運維人員,服務出現(xiàn)異常,然后進行通知(微信、郵件、短信、釘釘?shù)龋┛梢苑浅?焖偻ㄖ竭\維人員,相當報警功能,接下來通過本文給大家介紹SpringBoot Admin健康檢查的相關(guān)知識,一起看看吧
    2021-06-06
  • SpringBoot使用Kaptcha實現(xiàn)驗證碼的生成與驗證功能

    SpringBoot使用Kaptcha實現(xiàn)驗證碼的生成與驗證功能

    這篇文章主要介紹了SpringBoot使用Kaptcha實現(xiàn)驗證碼的生成與驗證功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Java追加文件內(nèi)容的三種方法實例代碼

    Java追加文件內(nèi)容的三種方法實例代碼

    本篇文章主要介紹了Java追加文件內(nèi)容的三種方法實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • Java詳解實現(xiàn)ATM機模擬系統(tǒng)

    Java詳解實現(xiàn)ATM機模擬系統(tǒng)

    這篇文章主要為大家詳細介紹了如何利用Java語言實現(xiàn)控制臺版本的ATM銀行管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • 逆轉(zhuǎn)交替合并兩個鏈表的解析與實現(xiàn)

    逆轉(zhuǎn)交替合并兩個鏈表的解析與實現(xiàn)

    本篇文章主要介紹了將兩個鏈表逆轉(zhuǎn)交替合并的實現(xiàn)思路與方法,需要的朋友可以參考下
    2015-07-07
  • 一篇文章帶你搞定JAVA泛型

    一篇文章帶你搞定JAVA泛型

    泛型是Java中的高級概念,也是構(gòu)建框架必備技能,比如各種集合類都是泛型實現(xiàn)的,今天詳細聊聊Java中的泛型概念,希望有所收獲
    2021-07-07
  • java操作xml的方法匯總及解析

    java操作xml的方法匯總及解析

    這篇文章主要介紹了java操作xml的方法匯總及解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-11-11
  • Maven實現(xiàn)項目構(gòu)建工具

    Maven實現(xiàn)項目構(gòu)建工具

    本文主要介紹了Maven實現(xiàn)項目構(gòu)建工具,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07

最新評論

胶南市| 古交市| 颍上县| 吴堡县| 平舆县| 宣威市| 齐河县| 大兴区| 汶上县| 盱眙县| 皋兰县| 梅州市| 台南县| 鹤峰县| 韩城市| 汤原县| 巧家县| 阳城县| 广丰县| 商洛市| 延安市| 东城区| 东平县| 准格尔旗| 溆浦县| 石楼县| 芜湖市| 文昌市| 岐山县| 攀枝花市| 天津市| 师宗县| 无锡市| 赣榆县| 改则县| 蒲城县| 抚州市| 札达县| 肥乡县| 喜德县| 车险|