美文网首页
spring aop配置中的坑

spring aop配置中的坑

作者: kylinxiang | 来源:发表于2017-09-23 16:48 被阅读28次

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 xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <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相同。

相关文章

网友评论

      本文标题:spring aop配置中的坑

      本文链接:https://www.haomeiwen.com/subject/ccicextx.html