《Java程序猿面试笔试宝典》之 什么是AOP

AOP(Aspect-Oriented Programming。面向切面编程)是对面向对象开发的一种补充,它同意开发者在不改变原来模型的基础上动态地改动模型从而满足新的需求。比如。在不改变原来业务逻辑模型的基础上能够动态地添加日志、安全或异常处理的功能。

以下介绍一个在Spring中使用AOP编程的简单样例。

(1)创建一个接口以及实现这个接口的类。TestAOPIn.java内容例如以下所看到的。

public interface TestAOPIn{

       public void doSomething();

}

TestAOPImpl.java内容例如以下所看到的。

public class TestAOPImpl implements TestAOPIn{

       public void doSomething(){

              System.out.println("TestAOPImpl:doSomething");

       }

}

(2)配置SpringConfig.xml,使得这个类的实例化对象能够被注入到使用这个对象的Test类中。

<?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="testAOPBean" class="org.springframework.aop.framework.ProxyFactoryBean">

    <property name=”target”>

       <bean class=”testAOPIn” singleton=”false” />

    </property>

</bean>

</beans>

(3)在完毕配置文件后,编写測试代码例如以下所看到的。

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test {

   public static void main(String[] args) {

     ApplicationContext  ctx = new FileSystemXmlApplicationContext("SpringConfig.xml ");

     TestAOPIn t = (TestAOPIn)ctx.getBean("testAOPBean"); 

     t.doSomething();

  }

}

程序输出结果为:

TestAOPImpl:doSomething

当编写完这个模块后,开发者须要添加对doSomething()方法调用的跟踪。也就是说要跟踪该方法什么时候被调用的以及什么时候调用结束的等内容。当然,使用传统的方法也能够实现该功能,可是却会产生额外的开销。即须要改动已存在的模块。所以,能够採用例如以下的方式来实现这个功能。

public class TestAOPImpl implements TestAOPIn{

       public void doSomething(){

              System.out.println("beginCall  doSomething");

              System.out.println("TestAOPImpl:doSomething");

              System.out.println("endCall  doSomething");

       }

}

此时能够採用AOP的方式来完毕。它在不改动原有模块的前提下能够完毕同样的功能。实现原理例如以下图所看到的。

为此须要提供用来跟踪函数调用的类,traceBeforeCall.java文件内容例如以下所看到的。

public class  traceBeforeCall implements MethodBeforeAdvice {

  public void beforeCall (Method arg0, Object[] arg1, Object arg2) throws Throwable {

       System.out.println("beginCall doSomething ");

  }

}

traceEndCall.java文件内容例如以下所看到的。

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class  traceEndCall  implements AfterReturningAdvice {

  public void afterCall(Object arg0, Method arg1, Object[] arg2, Object arg3)  throws Throwable {

    System.out.println("endCall doSomething);

  }

}

仅仅须要在配置文件里配置在调用doSomething()方法之前须要调用traceBeforeCall类的beforeCall()方法,在调用doSomething()方法之后须要调用traceEndCall类的afterCall方法,Spring容器就会依据配置文件在调用doSomething()方法前后自己主动调用对应的方法。通过在beforeCall()方法和afterCall()方法中加入跟踪的代码就能够满足对doSomething()方法调用的跟踪要求,同一时候还不须要更改原来已实现的代码模块。


出自新书《Java程序猿面试笔试宝典》官网

原文地址:https://www.cnblogs.com/yfceshi/p/7283240.html