AOP是Spring框架面向切面的编程思想,AOP采用一种称为“横切”的技术,将涉及多业务流程的通用功能抽取并单独封装,形成独立的切面,在合适的时机将这些切面横向切入到业务流程指定的位置中。
具体使用方法:
配日文件中进行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.hellojava"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--aop 配置 proxy-target-class="true" -->
<!--<aop:config proxy-target-class="false">
<!–pointcut 切入点 定义切入点 id="切入点的唯一标识"
expression –>
<aop:pointcut id="point1" expression="execution(* com.hellojava.business.IService.save())"/>
<!–定义切面 ref="切面类id为printLog对象"–>
<aop:aspect ref="printLog">
<!– before 之前 method="把切面类的那个方法"–>
<!– <aop:before method="methodBefore" pointcut-ref="point1"></aop:before>
<aop:after method="methodAfter" pointcut-ref="point1"></aop:after>–>
<aop:around method="methodAround" pointcut-ref="point1"></aop:around>
</aop:aspect>
</aop:config>-->
</beans>
类中使用注解
@Component
@Aspect
public class PrintLog {
@Pointcut("execution(* com.hellojava.business.IService.save())")
public void beforeAdvice(){}
//
//
// @Before("beforeAdvice()")
public void methodBefore(){
System.out.println("方法之前");
}
// @After("beforeAdvice()")
public void methodAfter(){
System.out.println("方法之后");
}
@Around("beforeAdvice()")
public Object methodAround(ProceedingJoinPoint proceedingJoinPoint){
System.out.println("环绕方法之前");
Object obj=null;
try {
obj = proceedingJoinPoint.proceed();
}catch (Throwable e){
e.printStackTrace();
}
System.out.println("环绕方法之后");
return obj;
}
}