spring(15)——实现aop的第二种方式,通过自定义类来实现aop

1.自定义创建一个类,类中有两个方法

package com.lixv.log;

public class DiyPointCut {
    public void diyBefore(){
        System.out.println("方法执行前===============");
    }
    public void diyAfter(){
        System.out.println("方法执行后===============");
    }
}

2.在beans.xml中引入aop

<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"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

3.在beans.xml中定义bean,并使用aop来实现aop操作

<bean id="userService" class="com.lixv.service.UserServiceImpl"/>
<bean id="diyPointCut" class="com.lixv.log.DiyPointCut"/>
<aop:config>
    <aop:aspect ref="diyPointCut">
        <aop:pointcut id="point" expression="execution(* com.lixv.service.UserServiceImpl.*(..))"/>
        <aop:before method="diyBefore" pointcut-ref="point"/>
        <aop:after method="diyAfter" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>
  1. aop:aspect的ref属性指向切面(一个类,即我们第一步创建的类)。
  2. aop:pointcut配置需要加日志的方法
  3. aop:before的method指向切面中的一个方法,在aop:pointcut指向的方法执行之前调用
  4. aop:after的method指向切面中的一个方法,在aop:pointcut指向的方法执行之后调用

4.测试

@Test
    public void test2(){
        ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) classPathXmlApplicationContext.getBean("userService");
        userService.add(5);
    }

5.运行结果

在这里插入图片描述

6.注意

  1. 这种实现没有第一种方法(通过继承spring中的接口实现的方法)厉害,不能够获取目标方法的反射等信息。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子 旭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值