美文网首页
AOP(面向切面编程)

AOP(面向切面编程)

作者: Yanl__ | 来源:发表于2019-12-10 17:45 被阅读0次

aop命名空间依赖的jar:
1.aopalliance
2.aspectjewaver

步骤

1.导入jar包



确定demo2为切点,在其前后加前置通知与后置通知

2.新建通知类
2.1 新建前置通知类参数

2.1.1 arg0: 切点方法对象Method 对象
2.1.2 arg1: 切点方法参数
2.1.3 arg2:切点在哪个对象中

2.2 新建后置通知类

2.2.1 arg0: 切点方法返回值
2.2.2 arg1:切点方法对象
2.2.3 arg2:切点方法参数
2.2.4 arg3:切点方法所在类的对象


3.配置Spring配置文件
3.1 引入aop 命名空间
3.2 配置通知类的<bean>
3.3 配置切面
3.4 * 通配符,匹配任意方法名,任意类名,任意一级包名
demo2()方法中是无参的,就只匹配无参的方法
"execution(* com.steer.test.Demo.*())":拦截所有Demo中的无参方法
<aop:pointcut id="mypointcut" expression="execution(* com.steer.test.Demo.demo2())"/>

3.5 如果希望匹配任意方法参数(..)
"execution(* com.steer.test.Demo.*())":拦截所有Demo中的所有方法(有参与无参)

<?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:lang="http://www.springframework.org/schema/lang"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang
        https://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--    aop的配置-->
    <!--    在bean上中添加    -->
    <!--    xmlns:aop="http://www.springframework.org/schema/aop"-->
    <!--    在schemaLocation中添加下面两个地址-->
    <!--    http://www.springframework.org/schema/aop-->
    <!--    https://www.springframework.org/schema/aop/spring-aop.xsd-->
    <bean id="mybefore" class="com.steer.advice.MyBeforeAdvice"></bean>
    <bean id="myafter" class="com.steer.advice.MyAfterAdvice"></bean>

    <!--        配置切点与前后通知-->
    <aop:config>
        <!--            切点-->
        <aop:pointcut id="mypointcut" expression="execution(* com.steer.test.Demo.demo2())"/>
        <!--            前置通知与后置通知-->
        <aop:advisor advice-ref="mybefore" pointcut-ref="mypointcut"></aop:advisor>
        <aop:advisor advice-ref="myafter" pointcut-ref="mypointcut"></aop:advisor>
    </aop:config>

    <bean id="demo" class="com.steer.test.Demo"></bean>
</beans>

4.编写测试代码

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        Demo demo = ac.getBean("demo", Demo.class);

        demo.demo1();
        demo.demo2();
        demo.demo3();
    }
}

相关文章

网友评论

      本文标题:AOP(面向切面编程)

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