AOP浅析
想必大家对OOP都不陌生,就是面向对象编程.其实aop也没很多人说的那么神秘.有很多文章中都把AOP 说成是面向方面编程,就我感觉来说面向方面这个词不见得那么恰当,并且容易让人产生误解,(:让人会想方面到底是什么呢)。OOP和AOP之间也没有什么前因后果的关系。
为避免晦涩的词语解释,下面我就用一下小例子来说明用动态代理来实现AOP,
Business.class
BusinessImpl.class
LogHandler.class
Main.class
为避免晦涩的词语解释,下面我就用一下小例子来说明用动态代理来实现AOP,
Business.class
- package aop;
- public interface Business {
- public void print();
- }
package aop;
public interface Business {
public void print();
}
BusinessImpl.class
- package aop;
- import java.util.logging.Logger;
- public class BusinessImpl implements Business {
- private Logger logger = Logger.getLogger(this.getClass().getName());
- public void print() {
- // System.out.println("Doing...");
- logger.info("Doing .....");
- }
- }
package aop;
import java.util.logging.Logger;
public class BusinessImpl implements Business {
private Logger logger = Logger.getLogger(this.getClass().getName());
public void print() {
// System.out.println("Doing...");
logger.info("Doing .....");
}
}
LogHandler.class
- package aop;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.util.logging.Logger;
- public class LogHandler implements InvocationHandler {
- private Logger logger = Logger.getLogger(this.getClass().getName());
- private Object delegate;
- public LogHandler(Object delegate) {
- this.delegate = delegate;
- }
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object object = null;
- try {
- logger.info("start" + method);
- object = method.invoke(delegate, args);
- logger.info("end" + method);
- } catch(Exception e) {
- logger.info("Exception");
- }
- return object;
- }
- }
package aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
public LogHandler(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object object = null;
try {
logger.info("start" + method);
object = method.invoke(delegate, args);
logger.info("end" + method);
} catch(Exception e) {
logger.info("Exception");
}
return object;
}
}
Main.class
- package aop;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Proxy;
- public class Main {
- public static void main(String[] args) {
- Business business = new BusinessImpl();
- InvocationHandler handler = new LogHandler(business);
- System.out.println(business.getClass().getInterfaces());
- Business proxy = (Business) Proxy.newProxyInstance( business.getClass().getClassLoader(),
- business.getClass().getInterfaces(), handler);
- proxy.print();
- }
- }