spring -7 aop编码补充注解实现

目录

 

XML形式的编码回顾

注解方式的使用


XML形式的编码回顾

package aop;

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

public class MyAspect implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Object ret = null;
        System.out.println("运行在原始方法之前");
        ret = methodInvocation.proceed();
        System.out.println("运行在原始方法之后");
        return ret;
    }
}

XML中配置

<!--    原始对象-->
    <bean id="userDao" class="core.UserDaoImpl"></bean>
<!--    额外功能-->
    <bean id="around" class="aop.MyAspect"></bean>

<!--Proxy -target-class 默认false,运行JDK,true,运行cglib-->
    <aop:config proxy-target-class="true">
<!--        定义切入点-->
        <aop:pointcut id="pc" expression="within(core..*)"/>
<!--        组装-->
        <aop:advisor advice-ref="around" pointcut-ref="pc"></aop:advisor>
    </aop:config>

注解方式的使用

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
 * aop额外功能 类注解
 * 表示切面类
 */
@Aspect
public class MyAspect1 {
    /**
     * 这个方法必须是空实现,返回值是void
     */
    @Pointcut("within(core..*)")
    public void pointcut(){};
    /**
     * 这是自定义aop实现类额外功能方法,必须加上@Around注解
     * @param joinPoint 这个参数的作用同MethodInterceptor【spring】中MethodInvocation methodInvocation
     * @return 原始方法运行结果的返回值
     */

//    该注解表示额外功能类,里面的value值是切入点表达式
//    @Around("within(core..*)")
//    为了其他的额外功能重用切入点,避免重复的书写切入点
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret = null;
        System.out.println("原始方法运行之前");
        ret = joinPoint.proceed();
        System.out.println("原始方法运行之后");
        return ret;
    }
}

配置文件中:

<!--    原始对象-->
    <bean id="userDao" class="core.UserDaoImpl"></bean>
<!--额外功能 包括了切入点。-->
    <bean id="around" class="aop.MyAspect1"></bean>
<!--自动组装,proxy-target-class指定代理类型 cglib true JDK false-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值