设为首页 加入收藏

TOP

springboot~aop方法拦截Aspect和InvocationHandler的理解
2023-09-09 10:25:51 】 浏览:39
Tags:springboot aop 方法拦 Aspect InvocationHandler

在 Spring 中,@Autowired 注解的使用在不同的上下文中会产生不同的效果,这取决于所在的组件或类是否由Spring管理。

  1. @Aspect 注解的使用@Aspect 注解通常用于声明切面,而切面是 Spring 管理的组件。因此,@Autowired 注解可以直接用于切面类,以注入其他 Spring 托管的 bean。Spring AOP通过代理机制实现,切面类被 Spring 托管,因此可以利用 Spring 的依赖注入功能。

    @Aspect
    @Component
    public class MyAspect {
        @Autowired
        private MyService myService;
    
        // ...
    }
    
  2. InvocationHandler 接口的实现类InvocationHandler 接口的实现类通常不是由 Spring 管理的,它们是标准 Java 类。在这种情况下,Spring 的依赖注入机制不会自动生效,因为 Spring 无法感知和管理这些类。如果你在 InvocationHandler 实现类中需要依赖注入的功能,你需要手动注入依赖或者在创建代理对象时进行注入。

    public class MyInvocationHandler implements InvocationHandler {
        private final MyService myService;
    
        public MyInvocationHandler(MyService myService) {
            this.myService = myService;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // 在这里可以使用注入的 myService
            myService.doSomething();
            // ...
        }
    }
    

总之,差异在于组件是否由 Spring 管理。Spring 管理的组件可以利用 @Autowired 注解来实现依赖注入,而标准 Java 类通常需要手动注入依赖。@Aspect 注解的类通常是由 Spring 管理的,因此可以使用 @Autowired 注解来注入其他组件。而 InvocationHandler 接口的实现类通常不是由 Spring 管理的,所以不能直接使用 @Autowired 注解。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇开发软技能——Git Commit规范 下一篇Spring Boot中自动装配机制的原理

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目