如何自定义Java Interceptor

发布时间:2025-03-03 12:18:08 作者:小樊
来源:亿速云 阅读:111

在Java中,拦截器(Interceptor)通常用于在方法调用前后执行一些额外的逻辑。这种模式在AOP(面向切面编程)中非常常见。要自定义一个Java拦截器,你可以使用动态代理或者框架(如Spring AOP)来实现。下面是两种常见的方法:

方法一:使用Java动态代理

  1. 定义一个接口

    public interface MyService {
        void doSomething();
    }
    
  2. 实现接口

    public class MyServiceImpl implements MyService {
        @Override
        public void doSomething() {
            System.out.println("Doing something...");
        }
    }
    
  3. 创建一个拦截器类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class MyInterceptor implements InvocationHandler {
        private Object target;
    
        public MyInterceptor(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;
        }
    
        public static Object newProxyInstance(Object target) {
            return Proxy.newProxyInstance(
                    target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(),
                    new MyInterceptor(target)
            );
        }
    }
    
  4. 使用拦截器

    public class Main {
        public static void main(String[] args) {
            MyService target = new MyServiceImpl();
            MyService proxy = (MyService) MyInterceptor.newProxyInstance(target);
            proxy.doSomething();
        }
    }
    

方法二:使用Spring AOP

  1. 添加Spring依赖: 在你的pom.xml(如果你使用Maven)中添加Spring AOP依赖:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>
    
  2. 定义一个切面类

    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.After;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class MyAspect {
    
        @Before("execution(* com.example.MyService.doSomething(..))")
        public void beforeMethod() {
            System.out.println("Before method: doSomething");
        }
    
        @After("execution(* com.example.MyService.doSomething(..))")
        public void afterMethod() {
            System.out.println("After method: doSomething");
        }
    }
    
  3. 配置Spring应用上下文

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    
    @Configuration
    @ComponentScan(basePackages = "com.example")
    @EnableAspectJAutoProxy
    public class AppConfig {
    }
    
  4. 使用Spring容器获取Bean并调用方法

    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);
            MyService myService = context.getBean(MyService.class);
            myService.doSomething();
        }
    }
    

这两种方法都可以实现自定义拦截器,选择哪种方法取决于你的具体需求和项目架构。动态代理更加灵活,但需要手动处理代理逻辑;而Spring AOP则提供了更高级的功能和更简洁的配置方式。

推荐阅读:
  1. Mybatis自定义插件
  2. 如何在MyBatis中自定义Plugin插件

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

java

上一篇:怎样用Java Interceptor实现权限控制

下一篇:Java Interceptor工作原理是什么

相关阅读

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

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