您好,欢迎来到花图问答。
搜索
您的当前位置:首页spring aop配置中的坑

spring aop配置中的坑

来源:花图问答

spirng aop xml配置类型转换异常

场景:一场表演(Performance.perform())前后的观众行为(Audience类中定义的方法)

下面是Audience类的定义

package com.kylin.springaop.xml;

public class Audience {
    public void seatDown(){
        System.out.println("seat down");
    }

    public void claps(){
        System.out.println("claps claps claps");
    }

    public void returned(){
        System.out.println("returned");
    }

    public void exception(){
        System.out.println("exception");
    }
}

下面是Performance类

package com.kylin.springaop.xml;

public class Performance {
    public void performance(){
        System.out.println("perform");
    }
}

下面是xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans 
       
       
       
       
       
       

    <bean id="audience" class="com.kylin.springaop.xml.Audience"/>
    <bean id="performance" class="com.kylin.springaop.xml.Performance"/>

    <!--
        下面聊一个巨坑的东西,如果切点Bean的id和pointcut的id相同的话,就会出现
        Exception in thread "main" java.lang.ClassCastException:
        org.springframework.aop.aspectj.AspectJExpressionPointcut cannot be cast to com.kylin.springaop.xml.Performance
        spring将会认为上面配置的Bean是一个切点,然而切点是Bean中的perform()方法,就会出现
        类型转换异常。
    -->
    <!--错误配置,pointcut的id不能和Bean的id相同
    <aop:config>
        <aop:aspect ref="audience">
            <aop:pointcut id="performance"
                          expression="execution(* com.kylin.springaop.xml.Performance.performance(..))"/>
            <aop:before method="seatDown" pointcut-ref="performance"/>
            <aop:after method="claps" pointcut-ref="performance"/>
            <aop:after-returning method="returned" pointcut-ref="performance"/>
            <aop:after-throwing method="exception" pointcut-ref="performance"/>
        </aop:aspect>
    </aop:config>
    -->
    <aop:config>
        <aop:aspect ref="audience">
            <aop:pointcut id="perform"
                          expression="execution(* com.kylin.springaop.xml.Performance.performance(..))"/>
            <aop:before method="seatDown" pointcut-ref="perform"/>
            <aop:after method="claps" pointcut-ref="perform"/>
            <aop:after-returning method="returned" pointcut-ref="perform"/>
            <aop:after-throwing method="exception" pointcut-ref="perform"/>
        </aop:aspect>
    </aop:config>
</beans>

总的来说切点的id不能和bean的id相同。

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务