Spring中AOP实现的三种方式

  1. 实现Spring提供的接口
    依据要实现的功能,新建Class实现相应的接口,如实现MethodBeforeAdvice进行前置增强:
    建立接口的实现类:
package com.seu.diy;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class BeforeMethod implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        // method:要执行的目标对象方法
        // objects:方法参数
        // o:目标对象
        System.out.println("前置方法增强......");
    }
}

在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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userDao" class="com.seu.dao.UserDaoImpl"></bean>

    <bean id="userService" class="com.seu.service.UserServiceImpl">
        <property name="dao" ref="userDao"></property>
    </bean>

    <bean id="methodBefore" class="com.seu.diy.BeforeMethod"></bean>
    
    <!-- 配置aop -->
    <aop:config>
        <!-- 切入点 此处可以配置多个切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.seu.service..*.*(..))" />
        <!-- 将类切入到方法中 -->
        <aop:advisor advice-ref="methodBefore" pointcut-ref="pointcut" />
    </aop:config>
    
</beans>
  1. 无需实现接口,使用自定义类实现
package com.seu.diy;

public class diy {

    public void before(){
        System.out.println("执行前");
    }

    public void after(){
        System.out.println("执行后");
    }
}

xml中进行相应配置:

       利用切面配置 
    <aop:config>
        <aop:aspect id="myAspect" ref="diy">
            <aop:pointcut id="pointer" expression="execution(* com.seu.service..*.*(..))" />
            <aop:before pointcut-ref="pointer" method="before" />
        </aop:aspect>
    </aop:config>
  1. 注解
    使用注解实现,首先要创建自定义类,用@Aspect定义切面:
package com.seu.diy;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class diy {

    @Before("execution(* com.seu.service..*.*(..))")
    public void before(){
        System.out.println("执行前");
    }

    @After("execution(* com.seu.service..*.*(..))")
    public void after(){
        System.out.println("执行后");
    }
}

在xml中只需打开自动代理即可:

     注解配置 
    <aop:aspectj-autoproxy />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值