AOP的实现方式之四

等风来,不如追风去!

说明;

方式一 的service,serviceimpl相同,不在重复:

同样的, 先写一个方法拦截器的实现类,和方法三相同
package com.qianfeng.aop04;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * Created by Administrator on 2020/3/1.
 */
public class MyAscept implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("------before------");

        Object o = methodInvocation.proceed();

        System.out.println("------after------");
        return null;
    }
}

在配置配置文件

<?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">
    <!--注意以上添加了三处aop-->


    <bean id="us" class="com.qianfeng.aop04.UserServiceImpl"></bean>

    <bean id="ma" class="com.qianfeng.aop04.MyAscept"></bean>

    <!--proxy-target-class="true"表示强制使用cglig方式来实现动态代理-->
    <aop:config proxy-target-class="true">
        <!--
            定义一个aop切点,实现每个方法的代理
            第一个*表示方法的返回值,表示要代理的方法的返回值,如只代理返回值类型是boolean类型的方法时:
            <aop:pointcut id="pt" expression="execution(boolean com.qianfeng.aop04.*.*(..))"></aop:pointcut>
            如只代理参数列表是int
            <aop:pointcut id="pt" expression="execution(* com.qianfeng.aop04.*.*(int))"></aop:pointcut>
        -->
        <aop:pointcut id="pt" expression="execution(* com.qianfeng.aop04.*.*(..))"></aop:pointcut>
        <!--
            将MyAscept与切点关联起来
        -->
        <aop:advisor advice-ref="ma" pointcut-ref="pt"></aop:advisor>
    </aop:config>
</beans>

测试类:

package com.qianfeng.aop04;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * Created by Administrator on 2020/3/1.添加一个依赖
 * <p>
 * 注意:使用此方法的时候用到通配时必须要
 */
public class TestAop04 {
    @Test
    public void test() {
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("F:\\testmaven\\src\\main\\java\\com\\qianfeng\\aop04\\beans.xml");

        IUserService iUserService = applicationContext.getBean("us", IUserService.class);

        iUserService.deleteUser(001);
        iUserService.getAllUser();
        iUserService.saveUser(new Object());
        iUserService.updateUser(new Object());
    }
}

~over

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值