• 基于注解的AOP

AOP,意为面向切面编程。它可以在不修改源代码的情况下,给一个类中的函数动态添加程序的一种技术实现方式。

例如这样一个需求,我们需要对用户的增删改查操作进行日志的写入。

普通的做法是,我们写一个日志的类,然后再所有增删改查的操作中添加一个日志写入的方法。但是这样做的弊端就是你需要对程序所有的地方都加上增删改查的地方写上这个日志写入操作。如果程序非常庞大,那么我们就改死吧!

Java的AOP面向切面编程,很好的解决了这一个尴尬的问题。我们只需要写一个独立的类,经过一些注解等方式,Spring框架能自动根据注解在程序运行的时候帮助我们添加到上面的增删改查操作中加入日志写入操作。


  • 一个简单的基于注解的AOP实现

  1. 需要额外依赖的jar包
    aspectjrt.jar,cglib-nodep-2.1_3.jar,aspectjweaver-1.6.7.jar,aopalliance.jar,这几个依赖包你需要手动下载,然后才能通过注解的方式实现AOP,Spring没有自带这几个第三方的扩展包。

  2. 配置Bean.xml文件。必须要添加的是: xmlns:aop="http://www.springframework.org/schema/aop"http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    <aop:aspectj-autoproxy/>
    <bean id="UserAop" class="com.spring.aop.UserAop" ></bean> 这个是我们的一个AOP的类。



    1. <?xml version="1.0" encoding="UTF-8"?>  

    2. <beans    

    3.    xmlns="http://www.springframework.org/schema/beans"    

    4.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    

    5.    xmlns:context="http://www.springframework.org/schema/context"  

    6.    xmlns:aop="http://www.springframework.org/schema/aop"  

    7.    xsi:schemaLocation="http://www.springframework.org/schema/beans  

    8.    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  

    9.    http://www.springframework.org/schema/context  

    10.    http://www.springframework.org/schema/context/spring-context-2.5.xsd  

    11.    http://www.springframework.org/schema/aop  

    12.    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  

    13.    ">    

    14.    <context:annotation-config/>  

    15.    <aop:aspectj-autoproxy/>  

    16.    <bean id java教程,自学编程,青软培训