Spring AOP的几个概念
**1.切面(Aspect):**切面就是一个关注点的模块化,如事务管理、日志管理、权限管理等;
**2.连接点(Joinpoint):**程序执行时的某个特定的点,在Spring中就是一个方法的执行;
**3.通知(Advice):**通知就是在切面的某个连接点上执行的操作,也就是事务管理、日志管理等;
4.切入点(Pointcut):切入点就是描述某一类选定的连接点,也就是指定某一类要织入通知的方法;
**5.目标对象(Target):**就是被AOP动态代理的目标对象;
环绕增强
Before
前置增强处理,在目标方法前织入增强处理
后置增强处理,在目标方法正常执行(不出现异常)后织
AfterReturning
入增强处理
AfterThrowing
异常增强处理,在目标方法抛出异常后织入增强处理
最终增强处理,不论方法是否抛出异常,都会在目标方法
After
最后织入增强处理
Around
环绕增强处理,在目标方法的前后都可以织入增强处理
实例
创建接口
public interface IdoSomeService {
public void doSome();
}
创建原始对象并继承接口
public class IdoSomeServiceImpl implements IdoSomeService {
@Override
public void doSome(){
System.out.println("真实类");
}
}
创建切面增强实现类
public class MyBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("前置----");
}
}
编写applicationContext.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.xsd
<!--注入业务-->
<bean name="doSomeServiceImpl" class="com.SrpingProject.IdoSomeServiceImpl"></bean>
<!--增强,切面-->
<bean name="myBeforeAdvice" class="com.SrpingProject.MyBeforeAdvice"></bean>
<!--使用代理工厂实现增强-->
<bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
<!--将增强和业务织入带一起-->
<property name="target" ref="doSomeServiceImpl"/>
<!--拦截器增强类-->
<property name="interceptorNames" value="myBeforeAdvice"/>
<!--更换代理方式proxyTargetClass 默认值为false默认是jdk动态代理,但是当目标对象没有接口时,自动改为cglib |-->
<property name="proxyTargetClass" value="true"/>
</bean>
</beans>
编写测试类
运行结果
异常增强