Spring面向切面编程到底怎么切?

  • Post author:
  • Post category:其他




Spring面向切面编程到底怎么切?

最近在搞Spring,作为spring的核心之一的aop,面向切面编程,相信有很多小伙伴都跟我一样很好奇面向切面编程是怎么切的,下面是我看了一些博客有所感悟写下来的;

	spring作为一个轻量级的框架,大大简化了代码的开发,说明不用这个框架也是可以实现想要的功能的,但是修改起来会污染源码;下面就引出了我想要表达的内容;
	面向切面怎么切?
	举个栗子:
	定义接口
public interface IAopDemo {
    void eat();

    void work();

    void sleep();
}

定义实现类:

public class AopDemo implements IAopDemo{
    @Override
    public void eat() {
        System.out.println("eat");
    }

    @Override
    public void work() {
        System.out.println("work");
    }

    @Override
    public void sleep() {
        System.out.println("sleep");
        throw new RuntimeException("exception in sleep Method");
    }
}
@Test
    public void testAopDemo1() {
        AopDemo aopDemo = new AopDemo();

aopDemo.eat();
aopDemo.work();

aopDemo.sleep();

添加怎么添?

代理类


public class AopDemoHandle implements InvocationHandler {
    private AopDemo aopDemo = new AopDemo();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Object invoke = null;
        try {
            beforeExecuteMethod(method);
            invoke = method.invoke(aopDemo, args);
            afterExecuteMethod(method);
        } catch (Exception e) {
            executeMethodCaught(e);
        }
        return invoke;
    }

    private void executeMethodCaught(Exception e) {
        System.out.println("execute method happened exception");
    }

    private void afterExecuteMethod(Method method) {
        System.out.println("after execute " + method.getName());
    }

    private void beforeExecuteMethod(Method method) {
        System.out.println("before execute " + method.getName());
    }
}

实现类

@Test
    public void testAopDemo2() {
        IAopDemo aopDemo = (IAopDemo) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IAopDemo.class}, new AopDemoHandle());
        aopDemo.eat();
        aopDemo.work();
        aopDemo.sleep();
    }



版权声明:本文为weixin_46034434原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。