Spring(使用XML方式的AOP)
阿新 • • 發佈:2018-02-11
sta epo lan throwable ref express odin name point
方法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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd "default-autowire="byName" > <context:annotation-config/> <context:component-scan base-package="com.daoan"/> <bean id="logIntercetor" class="com.daoan.aop.LogIntercetor"></bean> <aop:config> <!-- pointcut,在哪些方法上面加切面邏輯 --><aop:pointcut expression="execution(public * com.daoan.service..*.add(..))" id="servicePointcut"/> <!-- 加入聲明的切面對象 所參考的切面對象是logInterceptor --> <aop:aspect id="logAspect" ref="logInterceptor" > <!-- 在add方法執行之前,會先執行LogIntercetor下面的before()方法 --> <aop:before method="before" pointcut-ref="servicePointcut" /> </aop:aspect> </aop:config> </beans>
package com.daoan.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//@Aspect
//@Component
public class LogIntercetor {
//(在方法執行之前先執行before()方法,如果需要把該邏輯織入到某個類的某個方法上,那個對象必須是spring管理起來的)
// @Before("execution(public * com.daoan.service..*.add(..))")
public void before() {
System.out.println("method before");
}
//方法正常運行完成之後
// @Around("execution(public * com.daoan.service..*.add(..))")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
方法2:
<context:annotation-config/> <context:component-scan base-package="com.daoan"/> <bean id="logIntercetor" class="com.daoan.aop.LogIntercetor"></bean> <aop:config> <!-- 加入聲明的切面對象 所參考的切面對象是logInterceptor --> <aop:aspect id="logAspect" ref="logInterceptor" > <!-- 在add方法執行之前,會先執行LogIntercetor下面的before()方法 --> <aop:before method="before" pointcut="execution(public * com.daoan.service..*.add(..))" /> </aop:aspect> </aop:config>
Spring(使用XML方式的AOP)