导论:Aspect Oriented Programming(AOP)即面向切面编程。AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果。它使得代码更加灵活,并且提供了代码的重用性。
可以写普通JAVA类+配置文件的方式进行切面编程,也可以用注释(annotation)方式进行切面编程。本例中采用后者。
流程:
1、写特殊的JAVA类,它通过添加注释(annotation)方式,指定切面、切入点和通知----->
2、在配置文件中加入一行,以便打开aspectJ注解,使其自动生成代理------>
3、写目标类的目标方法----->
4、测试类中调用目标类的目标方法。
1、写特殊的JAVA类,它通过添加注释(annotation)方式
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
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.Service;
@Aspect
//指定这是一个其切面
public class myAnnotationAspect {
//指定切入点
@Pointcut("execution(* myTarena.*.*(..))")
public void myPointCut(){}
//指定通知以及通知的范围
@Before("myPointCut()")
public void beforeMethod(){
System.out.println("前置通知。。。");
}
@Around("myPointCut()")
public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕通知上。。。");
Object obj=pjp.proceed();
System.out.println("环绕通知下。。。");
return obj;
}
@After("myPointCut()")
public void afterMethod(){
System.out.println("后置通知。。。");
}
}
2、在配置文件中加入一行,以便打开aspectJ注解,使其自动生成代理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="myService" class="myTarena.MyService"></bean>
<bean id="myAnnotationAspect" class="myTarena.myAnnotationAspect"></bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
3、写目标类的目标方法
public class MyService implements IMyService {
public void regist(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("----执行注册操作----");
}
}
4、测试类中调用目标类的目标方法。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("aop-aspect.xml");
IMyService myService=(IMyService) ctx.getBean("myService");
myService.regist();
}
}