Spring AOP
1. 导入pom配置
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2. applicationContext.xml配置
<!--导入bean对象-->
<bean id="userDao" class="com.c21w.dao.impl.UserDaoImpl"></bean>
<bean id="after" class="com.c21w.dao.aop.After"></bean>
<bean id="before" class="com.c21w.dao.aop.Before"></bean>
<!--配置约束-->
<aop:config>
<!--设置切入点-->
<aop:pointcut id="point" expression="execution(* com.c21w.dao.impl.UserDaoImpl.*(..))"/>
<!--设置执行环绕-->
<aop:advisor advice-ref="after" pointcut-ref="point"></aop:advisor>
<aop:advisor advice-ref="before" pointcut-ref="point"></aop:advisor>
</aop:config>
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//方法执行前调用
public class Before implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "准备执行" + method.getName() + "方法");
}
}
//========================================================================================================
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
//方法执行之后调用
public class After implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println(o1.getClass().getName() + "执行了" + method.getName() + "方法并且返回值是" + o);
}
}
或使用自定义增强类
<!--导入bean对象-->
<bean id="userDao" class="com.c21w.dao.impl.UserDaoImpl"></bean>
<!--增强类-->
<bean id="proxy" class="com.c21w.dao.aop2.Proxy"></bean>
<!--配置约束-->
<aop:config>
<!--自定义切面-->
<aop:aspect ref="proxy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.c21w.dao.impl.UserDaoImpl.*(..))"/>
<!--通知(切入的位置和方法)-->
<aop:after method="after" pointcut-ref="point"></aop:after>
<aop:before method="before" pointcut-ref="point"></aop:before>
</aop:aspect>
</aop:config>
public class Proxy {
public void after(){
System.out.println("执行了after方法");
}
public void before(){
System.out.println("执行了before方法");
}
}
注解实现
<!--导入bean对象-->
<bean id="userDao" class="com.c21w.dao.impl.UserDaoImpl"></bean>
<!--开启注解支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--导入注解对象-->
<bean id="ann" class="com.c21w.dao.aop3.AnnotationProxy"></bean>
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
// 标注这个类是一个切面
@Aspect
public class AnnotationProxy {
// 设置切入点
@After("execution(* com.c21w.dao.impl.UserDaoImpl.*(..))")
public void after(){
System.out.println("========after=======");
}
// 设置切入点
@Before("execution(* com.c21w.dao.impl.UserDaoImpl.*(..))")
public void before(){
System.out.println("=======before=======");
}
}