AOP
AOP的常用术语
1)切面
切面( Aspect )是指封装横切到系统功能(例如事务处理)的类。
2)连接点
连接点 (Joinpoint )是指程序运行中的 些时间点,例如方法的调用或异常的抛出。
3)切人点
切入点 (Pointcut )是指需要处理的连接点。在 Spring AOP 中,所有的方法执行都是连接点,而切入点是一个描述信息,它修饰的是连接点,通过切入点确定哪些连接点需要被处理。
4)通知
通知( Advice )是由切面添加到特定的连接点(满足切入点规则)的一段代码,即在定义好的切入点处所要执行的程序代码,可以将其理解为切面开启后切面的方法,因此通知是切面的具体实现。
5)引人
引入( Introduction )允许在现有的实现类中添加自定义的方法和属性。
6)目标对象
目标对象( Target Object )是指所有被通知的对象。如果 AOP 框架使用运行时代理的方式(动态的 AOP )来实现切面,那么通知对象总是 个代理对象。
7)代理
代理( Proxy )是通知应用到目标对象之后被动态创建的对象。
8)织人
织入( Weaving )是将切面代码插入到目标对象上,从而生成代理对象的过程。根据不同的实现技术, AOP 织入有三种方式:编译期织入, 需要有特殊 Java 编译器;类装载期织入,需要有特殊的类装载器;动态代理织入,在运行期为目标类添加通知生成子类的方式。 SpringAOP 框架默认采用动态代理织入,而 AspectJ采用编译期织入和类装载期织入。
通知类型
根据 Spring 通知在目标类方法中的连接点位置,通知可以分为6类型
1)环绕通知
环绕通知( org .aopalliance.intercept.Methodlnterceptor )是在目标方法执行前和执行后实施增强,可应用于日志记录、 事务处理等功能.
public interface ISomeService {
void doFirst();
String doSecond();
}
public class SomeServiceImpl implements ISomeService{
public void doFirst(){
System.out.println("执行dofirst");
}
public String doSecond(){
System.out.println("执行doSecond");
return "abcde";
}
}
public class methodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("目标方法执行之前:");
//调用了目标方法
Object result=invocation.proceed();
System.out.println("目标方法执行之后:");
//返回执行方法的结果
if(result!=null) {
result =((String)result).toUpperCase();
}
return result;
}
}
<?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:tx="http://www.springframework.org/schema/tx"
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.xsd
">
<!-- 注册目标对象 -->
<bean id="someService" class="com.spring.aop04.SomeServiceImpl"/>
<!-- 注册切面:通知 -->
<bean id="myAdice" class="com.spring.aop04.methodInterceptor"/>
<!-- 生成代理对象 -->
<bean id="ServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="someService"/>
<property name="interceptorNames" value="myAdice"/>
</bean>
</beans>
@Test
public void test01() {
ApplicationContext ctx=new ClassPathXmlApplicationContext("com/spring/aop04/applicationContext.xml");
ISomeService hello=(ISomeService) ctx.getBean("ServiceProxy");
hello.doFirst();
System.out.println("=============");
String result= hello.doSecond();
System.out.println(result);
}}
2)前置通知
前置通知( org springframework.aop.Met odBeforeAdvice 是在 目标方法执行前实施增
强,可应用于权限管理等功能。
public interface ISomeService {
void doFirst();
void doSecond();
}
public class SomeServiceImpl implements ISomeService{
public void doFirst(){
System.out.println("执行dofirst");
}
public void doSecond(){
System.out.