动态代理
jdk动态代理
1.使用的是Proxy类和invoiceationHandle接口
2.被代理类实现某一接口
3.所有public都会被拦截
CGLIB
1.生成目标类的子类 继承
2.如果目标类是final修饰的 ,不能代理
3.可以拦截的方法,不能是final, static 不能是private,不能是默认的
Aop 面向切面
<br /> 目的:为了增强代码的功能特点:事务处理 日志管理,权限控制等被Spring进行封装便于减少系统的重复代码,有利于扩展维护使用动态代理实现如果一个类实现了接口,那么Spring底层会使用JDK动态代理完成如果一个类没有实现接口,那么Spring底层使用CGLIb动态代理创建该类的子类概念:1.切入点(Pointcut) :就是说在那些类,那些方法上进行切入2.增强(Advice):通知 在方法执行的什么时机,(在方法前,后)做什么(要增强的功能)3.切面(Aspect). =切入点+增强(通知) 针对哪个类,在什么时机做什么事。4.织入(WeAVing):就是将切面加到对象,并创建出代理对象的过程(Spring完成)
切面:是通知和切点的集合,通知和切点共同定义了切面的全部功能——它是什么,在何时何处完成其功能。
通知:就是我们编写的希望Aop时执行的那个方法。我们通过Aop希望我们编写的方法在目标方法执行前执行,或者执行后执行。
配置Aop
<!-- 配置AOP --><aop:config><!-- 配置一个切面,ref:做什么样的增强 --><aop:aspect ref="logmanmager"><!--切入点 包.类.方法 --><!--..代表任意的子包或任意的参数第一个*任意字符,表示返回值为任意的第二个*表示任意符合Dao结束的类第三个*表示任意的方法execution不能少--><aop:pointcut expression="execution(* com.zhiyou100.UserDao.*Dao.*(..))" id="pointcut"/><!-- 前置通知 --><aop:before method="beginWrite" pointcut-ref="pointcut"/><!--后置通知,当业务方法正常执行完毕 --><aop:after-returning method="upLoadlog" pointcut-ref="pointcut"/><!-- 异常通知,当业务方法出现异常时做增强 --><aop:after-throwing method="error" pointcut-ref="pointcut"/><!-- 最终通知,无论是否有异常,最终都要增强的代码 --><aop:after method="clear" pointcut-ref="pointcut"/><!-- 环绕通知,综合 类似方法放入替代,一般情况下,环绕通知必须满足以下特点1.方法必须返回一个Object类型2.方法第一个参数必须是ProceedingJoinPoint--><aop:around method="arroundMenthod" pointcut-ref="pointcut"/></aop:aspect></aop:config>
public class StudentMannager {public void strat() {System.out.println("日志开始");}public void upload() {System.out.println("日志加载");}public void error() {System.out.println("日志加载失败");}public void clear() {System.out.println("日志清理");}public void arround(ProceedingJoinPoint pro) {strat();try {pro.proceed();upload();} catch (Throwable e) {error();e.printStackTrace();}finally {clear();}}}
<bean id="studentmannager" class="com.zhiyou.dao.util.StudentMannager"/><bean id="studentDao" class="com.zhiyou.dao.impl.StudentDaoImpl"/><aop:config><aop:aspect ref="studentmannager"><aop:pointcut expression="execution(* com.zhiyou.dao.*Dao.*(..))" id="expointcut"/><aop:around method="arround" pointcut-ref="expointcut"/></aop:aspect></aop:config>
Test
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfigurationpublic class TestSpring {@Autowiredprivate StudentDao student;@org.junit.Testpublic void Test() {student.add();}}
