【Spring】面向切面编程AOP的简单理解及实现

AOP,面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP的主要功能:权限控制、事务管理 、日志打印、性能统计、异常处理等
AOP的三大点:
(1)关注点——重复代码
(2)切面——抽取重复代码
(3)切入点——拦截哪些方法
AOP的通知有:前置通知、后置通知、运行通知、异常通知、环绕通知

一、注解方式实现AOP编程

1、在配置文件中开启aop注解

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

2、在Aop文件中编写方法,添加注解(如:@Aspect、@Component、@Before等)

表达式execution(* cn.cxh.service..(…))这个表达式的意思是cn.cxh.service包下的文件都会被通知,如果想具体某个service的某个方法,可以这样写:execution(* cn.cxh.service.DeptService.add(…)),所以他的规则就是,那个不想具体,用*代替就可以了

@Aspect
@Component
public class Aop {
    @Before("execution(* cn.cxh.service.*.*(..))")
    public void bean(){
        System.out.println("----------前置通知-----------");
    }
    @After("execution(* cn.cxh.service.*.*(..))")
    public void commit(){
        System.out.println("----------后置通知-----------");
    }

    @AfterReturning("execution(* cn.cxh.service.*.*(..))")
    public void afterRun(){
        System.out.println("----------运行通知-----------");
    }

    @AfterThrowing("execution(* cn.cxh.service.*.*(..))")
    public void afterThrowing(){
        System.out.println("----------异常通知-----------");
    }

    @Around("execution(* cn.cxh.service.*.*(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("----------环绕通知(前)-----------");
        proceedingJoinPoint.proceed();
        System.out.println("----------环绕通知(后)-----------");
    }
}

二、XML方式实现AOP编程

1、配置文件中配置aop

这里配置每个通知的method要与实际方法名相对应

<bean id="aop" class="cn.cxh.util.AopXml"></bean>
    <aop:config>
        <!--定义一个切点表达式,拦截哪些方法-->
        <aop:pointcut id="pt" expression="execution(* cn.cxh.service.UserService.*(..))"/>
        <!--切面-->
        <aop:aspect ref="aop">
            <aop:around method="around" pointcut-ref="pt"/>
            <aop:before method="before" pointcut-ref="pt"/>
            <aop:after method="after" pointcut-ref="pt"/>
            <aop:after-returning method="afterReturning" pointcut-ref="pt"/>
            <aop:after-throwing method="afterThrowing" pointcut-ref="pt"/>
        </aop:aspect>
    </aop:config>

2、在文件AopXml中只写方法就可以了,不用添加注解

public class AopXml {
    public void before(){
        System.out.println("----------前置通知-----------");
    }
    public void after(){
        System.out.println("----------后置通知-----------");
    }
    public void afterReturning(){
        System.out.println("----------运行通知-----------");
    }
    public void afterThrowing(){
        System.out.println("----------异常通知-----------");
    }
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("----------环绕通知(前)-----------");
        proceedingJoinPoint.proceed();
        System.out.println("----------环绕通知(后)-----------");
    }
}

原创文章 255 获赞 116 访问量 19万+

猜你喜欢

转载自blog.csdn.net/cxh6863/article/details/104819556
今日推荐