使用Spring实现AOP

使用Spring实现AOP

导包

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

方式一:使用spring的API接口

目标方法接口:

public interface User {
    public void add();
}

目标方法的实现类:

public class UserImpl implements User{
    @Override
    public void add() {
        System.out.println("添加用户");
    }
}

前置增强:

public class Log implements MethodBeforeAdvice {
    /*
        method:目标对象的方法
        args:参数
        target:目标对象
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

后置增强:

public class AfterLog implements AfterReturningAdvice {
    //returnValue返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回结果为"+returnValue);
    }
}

引入aop依赖,注册bean,配置aop

<bean id="userImpl" class="cn.gbl.dao.UserImpl"/>
<bean id="log" class="cn.gbl.log.Log" />
<bean id="afterLoh" class="cn.gbl.log.AfterLog"/>

<!-- 配置aop   -->
<aop:config>
    <!--  切入点  execution():修饰词 返回值 类名 方法名 参数  -->
    <aop:pointcut id="pointcut" expression="execution(* cn.gbl.dao.UserImpl.*(..))"/>
    <!--执行环绕   -->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLoh" pointcut-ref="pointcut"/>
</aop:config>

方式二:自定义实现AOP

自定义类:

public class DiyPointCut {
    public void before(){
        System.out.println("方法执行前,执行这个方法");
    }
    public void after(){
        System.out.println("方法执行后,执行这个方法");
    }
}

注册bean,配置aop

<bean id="diy" class="cn.gbl.diy.DiyPointCut"/>

<aop:config>
    <aop:aspect ref="diy">
        <aop:pointcut id="pointcut" expression="execution(* cn.gbl.dao.UserImpl.*(..))"/>
        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

方式三:使用注解实现AOP

在配置文件中开启注解支持:

<context:component-scan base-package="cn.gbl"/>
<context:annotation-config/>
<aop:aspectj-autoproxy/>

自定义类并添加注解:

@Repository
@Aspect
public class DiyPointCut {
    @Before("execution(* cn.gbl.dao.UserImpl.*(..))")
    public void before(){
        System.out.println("方法执行前========");
    }
    @After("execution(* cn.gbl.dao.UserImpl.*(..))")
    public void after(){
        System.out.println("方法执行后=====");
    }
}
posted @ 2021-01-31 16:30  xxgbl  阅读(92)  评论(0)    收藏  举报