面向切面编程实际实际上就是动态代理。看图:
Target:目标类,需要被增强的类,也就是上面我们写的UserServiceImpl。
JointPoint:连接点,目标类上需要被增强的方法,(这些方法可以被增强,也可以不增强,也就是说目标类中所有的方法都可以称为是连接点)
PointCut:切入点,被增强的方法(已经确定这个方法要被增强),切入点就是一个连接点的子集
Advice:增强/通知,增强的代码,也就是上面将增强的代码凑成的一个类。类中的每个方法都代表一个增强的功能代码,这个类中的方法就被称为通知
weaving:织入,将切入点和通知结合,从没被增强到已经增强的过程
Aspect:切面,切入点和通知结合,切入点 和 通知点 多点形成面
UserServiceImpl.java(目标)
package nuc.test.aop;
public class UserServiceImpl {
public void add() {//(切点)
System.out.println("spring add");
}
}
MySpect.java(通知)
package nuc.test.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MySpect implements MethodInterceptor{
public Object invoke(MethodInvocation invocation) throws Throwable {
// TODO Auto-generated method stub
System.out.println("前");
Object obj = invocation.proceed();
System.out.println("后");
return obj;
}
}
beans-aop.xml
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd ">
<!-- bean definition & AOP specific configuration -->
<bean id="userServiceImplId" class="nuc.test.aop.UserServiceImpl"/>
<bean id="mySpect" class="nuc.test.aop.MySpect"/>
<aop:config>
<aop:pointcut expression="execution(* nuc.test.aop.UserServiceImpl.*(..))" id="myPoint"></aop:pointcut>
<aop:advisor advice-ref="mySpect" pointcut-ref="myPoint"></aop:advisor>
</aop:config>
</beans
MainApp.java
package nuc.test.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("beans-aop.xml");
UserServiceImpl u =(UserServiceImpl) ac.getBean("userServiceImplId") ;
u.add();
}
}