动态代理

jdk动态代理
1.使用的是Proxy类和invoiceationHandle接口
2.被代理类实现某一接口
3.所有public都会被拦截

CGLIB
1.生成目标类的子类 继承
2.如果目标类是final修饰的 ,不能代理
3.可以拦截的方法,不能是final, static 不能是private,不能是默认的

Aop 面向切面

  1. <br /> 目的:为了增强代码的功能
  2. 特点:事务处理 日志管理,权限控制等被Spring进行封装
  3. 便于减少系统的重复代码,有利于扩展维护
  4. 使用动态代理实现
  5. 如果一个类实现了接口,那么Spring底层会使用JDK动态代理完成
  6. 如果一个类没有实现接口,那么Spring底层使用CGLIb动态代理创建该类的子类
  7. 概念:
  8. 1.切入点(Pointcut) :就是说在那些类,那些方法上进行切入
  9. 2.增强(Advice):通知 在方法执行的什么时机,(在方法前,后)做什么(要增强的功能)
  10. 3.切面(Aspect). =切入点+增强(通知) 针对哪个类,在什么时机做什么事。
  11. 4.织入(WeAVing):就是将切面加到对象,并创建出代理对象的过程(Spring完成)


切面:是通知和切点的集合,通知和切点共同定义了切面的全部功能——它是什么,在何时何处完成其功能。

通知:就是我们编写的希望Aop时执行的那个方法。我们通过Aop希望我们编写的方法在目标方法执行前执行,或者执行后执行。

配置Aop

  1. <!-- 配置AOP -->
  2. <aop:config>
  3. <!-- 配置一个切面,ref:做什么样的增强 -->
  4. <aop:aspect ref="logmanmager">
  5. <!--切入点 包.类.方法 -->
  6. <!--
  7. ..代表任意的子包或任意的参数
  8. 第一个*任意字符,表示返回值为任意的
  9. 第二个*表示任意符合Dao结束的类
  10. 第三个*表示任意的方法
  11. execution不能少
  12. -->
  13. <aop:pointcut expression="execution(* com.zhiyou100.UserDao.*Dao.*(..))" id="pointcut"/>
  14. <!-- 前置通知 -->
  15. <aop:before method="beginWrite" pointcut-ref="pointcut"/>
  16. <!--后置通知,当业务方法正常执行完毕 -->
  17. <aop:after-returning method="upLoadlog" pointcut-ref="pointcut"/>
  18. <!-- 异常通知,当业务方法出现异常时做增强 -->
  19. <aop:after-throwing method="error" pointcut-ref="pointcut"/>
  20. <!-- 最终通知,无论是否有异常,最终都要增强的代码 -->
  21. <aop:after method="clear" pointcut-ref="pointcut"/>
  22. <!-- 环绕通知,综合 类似方法放入替代,一般情况下,环绕通知必须满足以下特点
  23. 1.方法必须返回一个Object类型
  24. 2.方法第一个参数必须是ProceedingJoinPoint
  25. -->
  26. <aop:around method="arroundMenthod" pointcut-ref="pointcut"/>
  27. </aop:aspect>
  28. </aop:config>
  1. public class StudentMannager {
  2. public void strat() {
  3. System.out.println("日志开始");
  4. }
  5. public void upload() {
  6. System.out.println("日志加载");
  7. }
  8. public void error() {
  9. System.out.println("日志加载失败");
  10. }
  11. public void clear() {
  12. System.out.println("日志清理");
  13. }
  14. public void arround(ProceedingJoinPoint pro) {
  15. strat();
  16. try {
  17. pro.proceed();
  18. upload();
  19. } catch (Throwable e) {
  20. error();
  21. e.printStackTrace();
  22. }finally {
  23. clear();
  24. }
  25. }
  26. }
  1. <bean id="studentmannager" class="com.zhiyou.dao.util.StudentMannager"/>
  2. <bean id="studentDao" class="com.zhiyou.dao.impl.StudentDaoImpl"/>
  3. <aop:config>
  4. <aop:aspect ref="studentmannager">
  5. <aop:pointcut expression="execution(* com.zhiyou.dao.*Dao.*(..))" id="expointcut"/>
  6. <aop:around method="arround" pointcut-ref="expointcut"/>
  7. </aop:aspect>
  8. </aop:config>

Test

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration
  3. public class TestSpring {
  4. @Autowired
  5. private StudentDao student;
  6. @org.junit.Test
  7. public void Test() {
  8. student.add();
  9. }
  10. }