spring框架AOP注解的使用

注解的优点:

1、XML配置起来有时候冗长,此时注解可能是更好的选择,如jpa的实体映射;

2、注解最大的好处就是简化了XML配置;

3、注解相对于XML的另一个好处是类型安全的,XML只能在运行期才能发现问题。

1.开启全局注解扫描

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


    <!--  开启注解扫描  -->
<context:component-scan base-package="com.java.spring"></context:component-scan>

    <!--  开启aop注解  -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>


</beans>

 

2.注解所有通知

/**
 * 切面类: 可以添加各种类型的通知
 */

@Component
@Aspect  //标记当前类是通知类
public class AllAdvice {

    //实现切点表达式的复用
    @Pointcut("execution(* *(..))")
    public void all(){}

    //前置通知
    @Before("all()")
    public void before(){
        System.out.println("------------前置通知-------------");
    }

    //后置通知
    @AfterReturning("all()")
    public void afterReturning(){
        System.out.println("------------后置通知-------------");
    }

    //异常通知
    @AfterThrowing("all()")
    public void afterThrowing(){
       System.out.println("------------异常通知-------------");
    }

    //最终通知
    @After("all()")
    public void after(){
        System.out.println("------------最终通知-------------");
    }

    //环绕通知
    @Around("all()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){

        try {
            System.out.println("------------环绕前置通知-------------");
            Object proceed = proceedingJoinPoint.proceed();
            System.out.println("------------环绕后置通知-------------");
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("------------环绕异常通知-------------");
        }finally {
            System.out.println("------------环绕最终通知-------------");
        }
        return null;
    }
}

 3.异常通知

    //异常通知   和后置通知永远只能执行一个
    @AfterThrowing("execution(* cn.kgc.spring.service.StudentServiceImpl.*(..))")
    public void exceptionMethod(){
        System.out.println("异常通知");
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值