spring aop 配置

Spring -Aop 入门
 
AOP 全名 Aspect-oriented programming Spring framework 是很有前途的 AOP 技术。作为一种非侵略性的,轻型的 AOP framework ,你无需使用预编译器或其他的元标签,便可以在 Java 程序中使用它。这意味着开发团队里只需一人要对付 AOP framework ,其他人还是像往常一样编程。
关键性概念:
1)          Advice 是代码的具体实现,例如一个实现日志记录的代码。
2)          Pointcut 是在将 Advice 插入到程序的条件。
3)           advisor 是把 pointcut advice 的组合在一起装配器。
 
图例:
你的程序可能如上,现在要在三个流程上同时加入日志控制和权限控制,如下:
 

 你的程序可能如上,现在要在三个流程上同时加入日志控制和权限控制,如下:

 

         其中拿日志为例,日志控制和流程之间的穿插点处叫做连接点( Joinpoint ),而 Advice 就是我们日志处理的具体代码, Pointcut 就是定义一个规则,对三个和业务有关的连接点进行过滤和匹配(例如我们对于业务 1 不做日志处理)。 Advisor 就是将符合的规则的剩下的两个连接点和具体的日志记录代码组合在一起。
 
三.  Spring-Aop 前置通知、后置通知、环绕通知、异常通知实现
 
我以 Spring In Action 提供的例子进行二次改造,完成我们自己的流程。业务流程很简单,顾客到商店买东西,店员根据顾客的需要给于顾客提供服务。实现方法前插入,方法后插入,环绕,异常四种。
 
       代码:
          建立一个用户类;
public class Customer {
     private String name = " 悠~游!";
     public String getName() {
          return name;
     }
}
三个产品
public class Cheese {
   public String toString(){
         return " 奶酪!";
   }
}
public class Pepper {
     public String toString(){
          return " 胡椒粉!";
     }
}
public class Squish {
     public String toString(){
          return " 果酱!";
     }
}
          建立一个接口;
public interface KwikEMart {
     Squish buySquish(Customer customer) throws KwikEMartException;
     Pepper buyPepper(Customer customer) throws KwikEMartException;
     Cheese buyCheese(Customer customer) throws KwikEMartException;
}
 
实现这个接口,我们实现三个方法,买奶酪,买胡椒粉,买果酱;
public class ApuKwikEMart implements KwikEMart {
     private boolean cheeseIsEmpty = false;
 
     private boolean pepperIsEmpty = false;
 
     private boolean squishIsEmpty = false;
 
     public Cheese buyCheese(Customer customer) throws NoMoreCheeseException{
 
          if (cheeseIsEmpty) {
               throw new NoMoreCheeseException();
          }
 
          Cheese s = new Cheese();
          System.out.println("-- 我想买:" + s);
          return s;
 
     }
 
     public Pepper buyPepper(Customer customer) throws NoMorePepperException{
 
          if (pepperIsEmpty) {
               throw new NoMorePepperException();
          }
 
          Pepper s = new Pepper();
          System.out.println("-- 我想买:" + s);
          return s;
 
     }
 
     public Squish buySquish(Customer customer) throws NoMoreSquishException{
 
          if (squishIsEmpty) {
               throw new NoMoreSquishException();
          }
 
          Squish s = new Squish();
          System.out.println("-- 我想买:" + s);
          return s;
 
     }
 
     public void setCheeseIsEmpty(boolean cheeseIsEmpty) {
          this.cheeseIsEmpty = cheeseIsEmpty;
     }
 
     public void setPepperIsEmpty(boolean pepperIsEmpty) {
          this.pepperIsEmpty = pepperIsEmpty;
     }
 
     public void setSquishIsEmpty(boolean squishIsEmpty) {
          this.squishIsEmpty = squishIsEmpty;
     }
 
}
环绕通知的实现,必须实现invoke方法,通过调用invoke.proceed()手工调用对象方法:
public class OnePerCustomerInterceptor implements MethodInterceptor {
    
     private Set customers=new HashSet();
 
     public Object invoke(MethodInvocation invoke) throws Throwable {
         
          Customer customer=(Customer)invoke.getArguments()[0];
          if(customers.contains(customer)){
               throw new KwikEMartException("One per customer.");
          }
         
          System.out.println(" 店员:"+customer.getName() + " ,Can I help you ?");
          Object squishee=invoke.proceed(); // 手工调用对象方法;
          System.out.println(" 店员:OK! " + customer.getName() + ".give you! " );
         
          customers.add(squishee);
 
          return squishee;
     }
}
前置通知的实现;
public class WelcomeAdvice implements MethodBeforeAdvice {
 
     public void before(Method method, Object[] args, Object target) throws Throwable {
         
          Customer customer = (Customer) args[0];
          System.out.println(" 店员::Hello " + customer.getName() + " . How are you doing?");
 
     }
}
public class Customer {
     private String name = " 悠~游!";
     public String getName() {
          return name;
     }
}
后置通知实现;
public class ThankYouAdvice implements AfterReturningAdvice {
 
     public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
         
          Customer customer = (Customer) args[0];
          System.out.println(" 店员:Thank you " + customer.getName() + " . Come again! " );
 
     }
}
系统异常处理通知实现;
public class KwikEmartExceptionAdvice implements ThrowsAdvice {
 
     public void afterThrowing(NoMoreSquishException e) {
          System.out.println(" 系统:NoMoreSquisheesException异常截获了: " + e.getMessage());
     }
     public void afterThrowing(NoMoreCheeseException e) {
          System.out.println(" 系统:NoMoreCheeseException异常截获了: " + e.getMessage());
     }
     public void afterThrowing(NoMorePepperException e) {
          System.out.println(" 系统:NoMorePepperException异常截获了: " + e.getMessage());
     }
}
自定义的异常接口;
public class KwikEMartException extends Exception {
 
     private static final long serialVersionUID = -3962577696326432053L;
 
     String retValue = "KwikEMartException 异常!";
 
     public KwikEMartException(String name) {
          retValue = name;
     }
     public KwikEMartException() {
 
     }
     public String getMessage() {
          return retValue;
     }
 
}
没有更多的奶酪异常;
public class NoMoreCheeseException extends KwikEMartException {
     private static final long serialVersionUID = -3961123496322432053L;
 
     String retValue = "NoMoreCheeseException 异常!";
 
     public NoMoreCheeseException() {
          super();
     }
 
     public NoMoreCheeseException(String name) {
          super(name);
     }
 
     public String getMessage() {
 
          return retValue;
     }
}
没有更多的胡椒粉异常;
public class NoMorePepperException extends KwikEMartException {
     private static final long serialVersionUID = -3961234696322432053L;
 
     String retValue = "NoMorePepperException 异常!";
 
     public NoMorePepperException() {
          super();
     }
 
     public NoMorePepperException(String name) {
          super(name);
     }
 
     public String getMessage() {
 
          return retValue;
     }
}
没有更多的果酱异常;
public class NoMoreSquishException extends KwikEMartException {
     private static final long serialVersionUID = -3121234696322432053L;
 
     String retValue = "NoMoreSquishException 异常!";
 
     public NoMoreSquishException() {
          super();
     }
 
     public NoMoreSquishException(String name) {
          super(name);
     }
 
     public String getMessage() {
 
          return retValue;
     }
}
运行实例类;
         
public class RunDemo {
 
               public static void kwikEMart() {
 
               ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("demo/kwikemart.xml");
 
                    // 如果你想通过类来引用这个的话,就要用到CGLIB.jar了,同时在代理工厂里面设置:
                    //<property name="proxyTargetClass" value="true" />
                    KwikEMart akem = (KwikEMart) context.getBean("kwikEMart");
    
                    try {
                         akem.buySquish(new Customer());
                         akem.buyPepper(new Customer());
                         akem.buyCheese(new Customer());
                    } catch (KwikEMartException e) {
                         // 异常已经被截获了,不信你看控制台!~;
                    }
               }
 
               public static void main(String[] args) {
                    kwikEMart();
               }
}
     Xml 文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 
 
<beans>
     <bean id="kwikEMartTarget" class="demo.ApuKwikEMart">
          <!--
               把这里注释去掉的话,程序调用的时候测试异常通知;
               <property name="cheeseIsEmpty">
                    <value>true</value>
               </property>
               <property name="pepperIsEmpty">
                    <value>true</value>
               </property>
               <property name="squishIsEmpty">
                    <value>true</value>
               </property>
          -->
     </bean>
 
     <!-- 方法调用前通知 -->
     <bean id="welcomeAdvice" class="demo.advice.WelcomeAdvice" />
     <!-- 方法调用后通知 -->
     <bean id="thankYouAdvice" class="demo.advice.ThankYouAdvice" />
     <!-- 环绕调用通知 -->
     <bean id="onePerCustomerInterceptor" class="demo.advice.OnePerCustomerInterceptor" />
     <!-- 异常调用通知 -->
     <bean id="kwikEmartExceptionAdvice" class="demo.advice.KwikEmartExceptionAdvice" />
    
     <bean id="kwikEMart" class="org.springframework.aop.framework.ProxyFactoryBean">
          <property name="proxyInterfaces" value="demo.KwikEMart" />
          <property name="interceptorNames">
               <list>
                   
                         <value>welcomeAdvice</value>
                         <value>thankYouAdvice</value>
                         <value>onePerCustomerInterceptor</value>
                         <value>kwikEmartExceptionAdvice</value>
                   
               </list>
          </property>
          <property name="target">
               <ref bean="kwikEMartTarget" />
          </property>
     </bean>
 
</beans>
     这个例子东西很多,不过每个类的代码都不大。如果你对 org.springframework.aop.framework.ProxyFactoryBean 不是很了解的话可以看我下篇尾处的介绍。 读清楚之后,我们运行RunDemo 类,查看控制台结果,如下:
 
店员::Hello 悠~游! . How are you doing?
店员:悠~游! ,Can I help you ?
-- 我想买:果酱!
店员:OK! 悠~游!.give you!
店员:Thank you 悠~游! . Come again!
店员::Hello 悠~游! . How are you doing?
店员:悠~游! ,Can I help you ?
-- 我想买:胡椒粉!
店员:OK! 悠~游!.give you!
店员:Thank you 悠~游! . Come again!
店员::Hello 悠~游! . How are you doing?
店员:悠~游! ,Can I help you ?
-- 我想买:奶酪!
店员:OK! 悠~游!.give you!
店员:Thank you 悠~游! . Come again!
 
    我们将 kwikEMartTarget 里面的注释去掉,测试异常实现,如下:
    
店员::Hello 悠~游! . How are you doing?
店员:悠~游! ,Can I help you ?
系统:NoMoreSquisheesException异常截获了: NoMoreSquishException 异常!
     好好理解一下,我就不废话了,我们进行下一节。
 
 
 
四.  Spring-Aop Pointcut +advice+Advisor 实现
 
我们修改我们的xml文档后如下:
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 
<beans>
 
     <bean id="kwikEMartTarget" class="demo.ApuKwikEMart"></bean>
 
     <!-- 环绕调用通知 -->
     <bean id="onePerCustomerInterceptor" class="demo.advice.OnePerCustomerInterceptor" />
 
     <!-- 使用NameMatchMethodPointcut -->
     <bean id="nameMatchfilterPointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
          <property name="mappedName">
               <!--
                    buy.* 以buy开头的方法;
               -->
               <value>buy*</value>
          </property>
     </bean>
 
     <!-- 使用Perl5RegexpMethodPointcut -->
     <bean id="regexpFilterPointcut" class="org.springframework.aop.support.Perl5RegexpMethodPointcut">
          <property name="pattern">
               <!--
                    .*buy.+ 以buy开头的方法;
                    .*buyS.+ 以buyS开头的方法;
               -->
               <value>.*suy.+</value>
          </property>
     </bean>
 
     <bean id="runDemofilterPointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
          <property name="pointcut">
               <ref bean=" nameMatchfilterPointcut" />
          </property>
          <property name="advice">
               <ref bean="onePerCustomerInterceptor" />
          </property>
     </bean>
     <bean id="kwikEMart" class="org.springframework.aop.framework.ProxyFactoryBean">
          <property name="proxyInterfaces" value="demo.KwikEMart" />
          <property name="interceptorNames">
               <list>
                    <value>runDemofilterPointcutAdvisor</value>
               </list>
          </property>
          <property name="target">
               <ref bean="kwikEMartTarget" />
          </property>
     </bean>
 
</beans>
 
运行,结果如下:
店员:悠~游! ,Can I help you ?
-- 我想买:果酱!
店员:OK! 悠~游!.give you!
店员:悠~游! ,Can I help you ?
-- 我想买:胡椒粉!
店员:OK! 悠~游!.give you!
店员:悠~游! ,Can I help you ?
-- 我想买:奶酪!
        店员:OK! 悠~游!.give you!
 
在这里简单说明一下xml文档: nameMatchfilterPointcut regexpFilterPointcut 是我们自己定义好规则的Pointcut。nameMatchfilterPointcut 根据mappedName来设置过滤规则, regexpFilterPointcut则是用pattern来设置过滤规则。runDemofilterPointcutAdvisor 则将我们的 Pointcut advice组合在一起。
读者可以自己修改runDemofilterPointcutAdvisorpointcut来切换不同的Pointcut。如果需要RegexpMethodPointcut 的子类的实现,必须要oro包支持。(注:RegexpMethodPointcut有俩个子类的实现,JdkRegexpMethodPointcut和Perl5RegexpMethodPointcut)。
     但是,如果我们想让我们的Advisor同时实现多个Pointcut+advice怎么办呢?利用Spring In Action里面的实例,我们来自己实现我们的Pointcut
 
    代码:
 
 
public class MyUnionPointcut implements Pointcut {
    
     private Pointcut delegate;
 
     public ClassFilter getClassFilter() {
          return getDelegate().getClassFilter();
     }
 
     private Pointcut getDelegate() {
          if (delegate == null) {
             

你可能感兴趣的:(spring,AOP,编程,bean,xml)