Spring AOP案例

1、IDEA下新建maven项目
项目目录
在这里插入图片描述

2、编写Func类,其中随便添加两个方法

package com.aop;

public class Func {
    public void add(){
        System.out.println("做点事情吧");
    }
    public void test(){
        System.out.println("这是一个测试方法");
    }
}

3、编写FuncPlus类,这是对Func类中方法的增强类

package com.aop;

public class FuncPlus {
    public void before(){
        System.out.println("开始前搞点事情");
    }
    public void after(){
        System.out.println("结束再搞点事情");
    }
}

4、编写配置文件beans.xml,通过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-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

    <!-- bean定义与aop配置 -->
    <bean id="func" class="com.aop.Func"></bean>
    <bean id="funcPlus" class="com.aop.FuncPlus"></bean>
    <!--配置aop操作-->
    <aop:config>
        <!--配置切入点,这里默认对Func类的所有方法增强,当然也可以增强单个方法,只需要修改路径就行-->
        <aop:pointcut id="point" expression="execution(* com.aop.Func.*())"  ></aop:pointcut>

        <!--配置切面 把增强用到方法后面-->
        <aop:aspect ref="funcPlus">
            <!--配置增强类,method为增强类中哪个方法为前置-->
            <aop:before method="before" pointcut-ref="point"></aop:before>
        </aop:aspect>
        <aop:aspect ref="funcPlus">
            <!--配置增强类,method为增强类中哪个方法为前置-->
            <aop:after method="after" pointcut-ref="point"></aop:after>
        </aop:aspect>
    </aop:config>

</beans>

5、编写测试类

package com.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        Func lock=(Func)context.getBean("func");
        lock.test();
    }
}

6、测试结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值