Java Interceptor如何实现方法拦截

发布时间:2025-04-13 15:57:31 作者:小樊
来源:亿速云 阅读:120

在Java中,实现方法拦截通常是通过动态代理(Dynamic Proxy)或者使用AOP(面向切面编程)框架,如Spring AOP。下面分别介绍这两种方法的实现。

1. 动态代理(Dynamic Proxy)

Java动态代理是一种运行时创建代理对象的技术,可以拦截并增强目标对象的方法调用。以下是使用动态代理实现方法拦截的步骤:

步骤1:定义接口

首先,定义一个接口,目标对象和代理对象都将实现这个接口。

public interface MyInterface {
    void doSomething();
}

步骤2:实现接口

创建一个实现该接口的目标对象。

public class MyInterfaceImpl implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("MyInterfaceImpl: doSomething");
    }
}

步骤3:创建代理处理器

创建一个实现了InvocationHandler接口的代理处理器类,用于拦截方法调用。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After method: " + method.getName());
        return result;
    }
}

步骤4:创建代理对象

使用Proxy.newProxyInstance()方法创建代理对象。

import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        MyInterface target = new MyInterfaceImpl();
        MyInvocationHandler handler = new MyInvocationHandler(target);
        MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                handler
        );
        proxy.doSomething();
    }
}

运行上述代码,输出结果如下:

Before method: doSomething
MyInterfaceImpl: doSomething
After method: doSomething

2. 使用Spring AOP

Spring AOP是一种基于代理的AOP框架,可以方便地实现方法拦截。以下是使用Spring AOP实现方法拦截的步骤:

步骤1:添加依赖

在项目的pom.xml文件中添加Spring AOP和AspectJ的依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>
</dependencies>

步骤2:定义接口和实现类

与动态代理示例相同,定义一个接口和实现类。

public interface MyInterface {
    void doSomething();
}

public class MyInterfaceImpl implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("MyInterfaceImpl: doSomething");
    }
}

步骤3:创建切面类

创建一个切面类,用于定义拦截规则和方法增强逻辑。

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;

@Aspect
public class MyAspect {
    @Before("execution(* MyInterface.doSomething(..))")
    public void beforeMethod() {
        System.out.println("Before method: doSomething");
    }

    @After("execution(* MyInterface.doSomething(..))")
    public void afterMethod() {
        System.out.println("After method: doSomething");
    }
}

步骤4:配置Spring容器

创建一个Spring配置类,启用AOP功能。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
    @Bean
    public MyInterface myInterface() {
        return new MyInterfaceImpl();
    }

    @Bean
    public MyAspect myAspect() {
        return new MyAspect();
    }
}

步骤5:运行程序

在主类中运行Spring容器,获取代理对象并调用方法。

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyInterface myInterface = context.getBean(MyInterface.class);
        myInterface.doSomething();
    }
}

运行上述代码,输出结果如下:

Before method: doSomething
MyInterfaceImpl: doSomething
After method: doSomething

通过以上两种方法,可以在Java中实现方法拦截。动态代理适用于简单的场景,而Spring AOP则提供了更强大的功能和更简洁的配置。

推荐阅读:
  1. java中mybatis拦截器的案例分析
  2. Java中inteceptor拦截器的原理是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:怎样用Java Interceptor处理异常

下一篇:Java Interceptor拦截器如何进行响应后处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》