java web开发(aop编程)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

        刚开始看到aop的时候,了解到它是面向切片,觉得还是挺拗口的。不知道应该怎么去理解怎么这么一个概念。后来想了一想,不如先看范例,直接从实例去理解aop或许更容易一点。

        目前参考的文章来自于这个链接,https://www.yiibai.com/spring/spring-aop-examples-advice.html从实例代码来看,aop更类似于用一种拦截器的方法去实现方法与方法直接调用的解耦。也就是说,方法之间的调用不再用硬编码的形式来实现,而是通过applicationContext.xml脚本配置的形式来完成。参考的实例内容略多,这里整理成一个完整的范例,大家可以逐步调试分析。

1、利用IDEA创建工程,选择“Spring”和“Application”

2、工程命名为Hello,创建完毕后,IDEA会自动下载好spring的jar库

3、创建CustomerService.java文件

public class CustomerService {
    private String name;
    private String url;

    public void setName(String name) {
        this.name = name;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void printName() {
        System.out.println("Customer name : " + this.name);
    }

    public void printURL() {
        System.out.println("Customer website : " + this.url);
    }

    public void printThrowException() {
        throw new IllegalArgumentException();
    }
}

4、编写Test测试类Test.java,这部分和之前差别不大

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });

        CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy");

        System.out.println("*************************");
        cust.printName();
        System.out.println("*************************");
        cust.printURL();
        System.out.println("*************************");
        try {
            cust.printThrowException();
        } catch (Exception e) {

        }
    }
}

5、准备各种各样的劫持类,比如事先劫持类、事后劫持类、异常劫持类、全部劫持类等

5.1 事前劫持类,继承自MethodBeforeAdvice

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class HijackBeforeMethod implements MethodBeforeAdvice
{
    @Override
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("HijackBeforeMethod : Before method hijacked!");
    }
}

5.2 事后劫持类,继承自AfterReturningAdvice

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class HijackAfterMethod implements AfterReturningAdvice
{
    @Override
    public void afterReturning(Object returnValue, Method method,
                               Object[] args, Object target) throws Throwable {
        System.out.println("HijackAfterMethod : After method hijacked!");
    }
}

5.3 异常劫持,继承自ThrowsAdvice

import org.springframework.aop.ThrowsAdvice;

public class HijackThrowException implements ThrowsAdvice {
    
    public void afterThrowing(IllegalArgumentException e) throws Throwable {
        System.out.println("HijackThrowException : Throw exception hijacked!");
    }
}

        注意到,这里的劫持方法没有@Override声明。

5.4 全部劫持,继承自MethodInterceptor


import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class HijackAroundMethod implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        System.out.println("Method name : "
                + methodInvocation.getMethod().getName());
        System.out.println("Method arguments : "
                + Arrays.toString(methodInvocation.getArguments()));

        // same with MethodBeforeAdvice
        System.out.println("HijackAroundMethod : Before method hijacked!");

        try {
            // proceed to original method call
            Object result = methodInvocation.proceed();

            // same with AfterReturningAdvice
            System.out.println("HijackAroundMethod : After method hijacked!");

            return result;

        } catch (IllegalArgumentException e) {
            // same with ThrowsAdvice
            System.out.println("HijackAroundMethod : Throw exception hijacked!");
            throw e;
        }
    }
}

        这个劫持方法是功能最完整的劫持方法。此外,在invoke方法中,也需要自己调用methodInvocation.proceed来调用被劫持的函数。此外,对于异常,invoke方法也可以做到劫持访问。

6、准备和创建applicaitonContext.xml文件,方法参照上一篇blog内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="customerService" class="CustomerService">
        <property name="name" value="baidu" />
        <property name="url"  value="www.baidu.com" />
    </bean>

    <bean id="hijackBeforeMethodBean" class="HijackBeforeMethod" />
    <bean id="hijackAfterMethodBean" class="HijackAfterMethod" />
    <bean id="hijackThrowExceptionBean" class="HijackThrowException" />
    <bean id="hijackAroundMethodBean" class="HijackAroundMethod" />

    <bean id="customerServiceProxy"
          class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>hijackBeforeMethodBean</value>
                <!--<value>hijackAfterMethodBean</value>
                <value>hijackThrowExceptionBean</value>
                <value>hijackAroundMethodBean</value>-->
            </list>
        </property>
    </bean>
</beans>

7、调试Test.java文件,不妨选择hijackBeforeMethodBean做测试,右击选择“Run Test.main函数”,

不出意外,就可以看到这样的打印结果,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌入式-老费

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值