zoukankan      html  css  js  c++  java
  • Spring中xml和注解方式使用AOP

    AOP是面向切面的编程。使用AOP的方式可以减少代码直接的耦合,后期维护起来较为方便。先看看最普通的Spring项目来配置AOP。

    需要的Jar包

    Spring需要的Jarspring-core.xx.jar,spring-beans.xx.jar,spring-context.xx.jar,spring-context-support.xx.jar,spring-expression.xx.jar

    AOP需要的包:spring-aop.xx.jar,spring-aspects.xx.jar,aopalliance.xx.jar,aspectjrt.jar,aspectjweaver.jar

    XML方式

    1. 配置好通知类,Spring的基础内容
    2. 使用xml
    <aop:config>
    		<aop:aspect id="time" ref="timeHandler1">
    			<!-- 前置通知 -->
                    <aop:before method="printStartTime" pointcut="execution(* com.xx.service.*.*(..))"/>
    			<!-- 后置通知 -->
                    <aop:after method="printEndTime" pointcut="execution(* com.xx.service.*.*(..))"/>
    		</aop:aspect>
    </aop:config>
    

    至此,切入成功。

    注解方式

    1. 在XML中开启AOP的自动代理(SpringBoot中默认开启的)
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
    1. 在类上注解@Aspect表示切面
    2. 在方法上注释@Before@After表示前置/后置通知。@Before("AOP表达式")

    定义切入点

    @Before@After中的表达式一样时,可以定义一个空的方法,作为切入点

    @Asspect
    public LogHandler{
        @PointCut("execution ...")
    	public void pointTest(){}
    	@Before("pointTest()") // @PointCut定义方法的名字
        public void printStartTime(){
            // ...
        }
        @After("pointTest()")
        public void printEndTime(){
            // ...
        }
    }
    

    环绕通知

    @Aspect
    public class TimeHandler {
    	@Around("execution(* com.xx.service.*.*(..))")
    	public void aroundTime(ProceedingJoinPoint pjp) {
    		System.out.println("环绕通知-->前");
    		try {
    			// 业务逻辑通过proceed()方法执行,相当于嵌入到这来
    			pjp.proceed();
    		} catch (Throwable e) {
    			e.printStackTrace();
    		}
    		System.out.println("环绕通知-->后");
    	}
    }
    
  • 相关阅读:
    P1410 子序列
    P1395 会议 (树形dp)
    P2580 于是他错误的点名开始了
    LC1127. 用户购买平台
    LC 1308. Running Total for Different Genders
    P1340 兽径管理 (最小生成树)
    P1330 封锁阳光大学 (二分图染色)
    CF1296F Berland Beauty (Tree, dfs/bfs, LCA)
    顺丰的Cookie条款
    服务器判断客户端的用户名和密码(token的身份验证)
  • 原文地址:https://www.cnblogs.com/to-red/p/12013578.html
Copyright © 2011-2022 走看看