当前位置: 首页 > biancheng >正文

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函数”,

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

相关文章:

  • 牛客练习赛#84 F 莫比乌斯反演+杜教筛+技巧+斐波那契数列和gcd的结论+矩阵快速幂
  • ZZNUOJ_用C语言编写程序实现1342:支配值数目(附完整源码)
  • java毕业设计后勤管理系统餐饮评价监督系统(附源码、数据库)
  • 前端基础学习笔记
  • 【TS】联合类型--类型断言--类型推断
  • 谈笑风声的秘密
  • QT影城网上售票系统
  • NetCDF数据在ArcMap中的使用
  • 打怪升级(考验思路)
  • 持续精进,改变自己