思尐-ChatGPT:你不懂可以来问我啊!

简介: 思尐-ChatGPT:你不懂可以来问我啊!

前言


Hello,大家好,我是java小面。不知道大家有没有自己实现过一个注解来替换Spring原有注解的经历,有人说Spring不是有注解给你用吗?干嘛还要特地的去实现一个来替换呢?

我们这次去请教ChatGPT如何写这么一段代码

只是可惜,它似乎不太能理解我的需求,还是自己来吧!

关于这个需求,小面当然不是闲得慌,我们做业务功能开发的时候,往往只懂得它该怎么用,却不知道它为什么可以这么用,它具体又是怎样的一个运行机制?

而当我们了解了它的一个机制后,不仅保持住了对技术专研的热情,还收获了成就感,让我们在技术的这条路上越走越远。

如何自定义依赖注入注解?

  1. 基于AutowiredAnnotationBeanPostProcessor实现
  2. 自定义实现
  1. InjectedElement
  2. InjectionMetadata
  3. InstantiationAwareBeanPostProcessor
  4. MergedBeanDefinitionPostProcessor
  5. 生命周期处理
  6. 元数据

这次我们拿最常见的一个注解进行开发。

举个例子

一、copy注解

这是一个大家都常用的注解

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
   /**
    * Declares whether the annotated dependency is required.
    * <p>Defaults to {@code true}.
    */
   boolean required() default true;
}

@Autowired最常用于依赖注入,但是大家都知道,注解是无法拓展的,如果大家想要拓展,唯一的方法就是copy一份一模一样的取代掉它的使用。

比如我重新定义一个Autowired注解且把它用于依赖注入中。

我们给他命名 MyAutowired

/**
 * 自定义注解
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Autowired
public @interface MyAutowired {
    /**
     * Declares whether the annotated dependency is required.
     * <p>Defaults to {@code true}.
     */
    boolean required() default true;
}

其他的和@Autowired一模一样,区别在于public上面把 Autowired注解标注上了。

因为Autowired本身拥有ElementType.ANNOTATION_TYPE就说明它允许被使用在注解上面

测试Demo

package org.example.definition;
import org.example.pojo.MyAutowired;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author Java面试教程
 * @date 2022-12-18 21:14
 */
@Configuration
public class Demo {
    @Bean
    public User User(){
        return new  User(1,"Java面试教程");
    }
    @Autowired
    private User user;
    @MyAutowired
    private User myUser;
    public static void main(String[] args)
    {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册当前类,主要目的是获取@Bean
        applicationContext.register(Demo.class);
        //启动应用上下文
        applicationContext.refresh();
        Demo bean = applicationContext.getBean(Demo.class);
        System.out.println("user对象:"+bean.user);
        System.out.println("myUser对象:"+bean.myUser);
        applicationContext.close();
    }
}

结果

Connected to the target VM, address: '127.0.0.1:65300', transport: 'socket'
user对象:User{id=1, name='Java面试教程'}
myUser对象:User{id=1, name='Java面试教程'}
Disconnected from the target VM, address: '127.0.0.1:65300', transport: 'socket'

说明拥有ElementType.ANNOTATION_TYPE的元标注可以通过这种方式来拓展开发。

二、自定义注解

接下来我们讲一下,用AutowiredAnnotationBeanPostProcessor怎么去实现自定义依赖注入注解

首先还是定义一个注解,这个注解不包含其他注解

/**
 * 自定义依赖注入注解
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomAutowired {
}

然后重新实现 AutowiredAnnotationBeanPostProcessor 的bean对象

@Bean(name = AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)
public static AutowiredAnnotationBeanPostProcessor beanPostProcessor(){
    AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
    Set<Class<? extends Annotation > > types = new LinkedHashSet<>(Arrays.asList(Autowired.class, MyAutowired.class, CustomAutowired.class));
    beanPostProcessor.setAutowiredAnnotationTypes(types);
    return beanPostProcessor;
}

AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME 是Autowired默认的Bean名称,所以我们重新,且把自己定义的CustomAutowired注入进去,那么我们之后使用@CustomAutowired的时候它就可以达到和Autowired一样的效果了。

Set<Class<? extends Annotation > > types = new LinkedHashSet<>(Arrays.asList(Autowired.class, MyAutowired.class, CustomAutowired.class));
    beanPostProcessor.setAutowiredAnnotationTypes(types);

如果types里只有CustomAutowired.class,没有Autowired.class, MyAutowired.class,那么原本使用@Autowired和@MyAutowired的对象,就只会拿到null,因为你重新覆盖的值里面没有他们。那么他们就不被归类到依赖注入的用法里面了。

感兴趣的可以自己试试运行,随便找一个类替换掉User就能执行了。

测试Demo

import static org.springframework.context.annotation.AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME;
/**
 * @author Java面试教程
 * @date 2022-12-26 21:14
 */
@Configuration
public class Demo {
    @Bean
    public User User(){
        return new User(1,"Java面试教程");
    }
    @Autowired
    private User user;
    @CustomAutowired
    private User customAutowiredUser;
    @MyAutowired
    private User myUser;
    @Bean(name = AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)
    public static AutowiredAnnotationBeanPostProcessor beanPostProcessor(){
        AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
        Set<Class<? extends Annotation > > types =
                new LinkedHashSet<>(Arrays.asList(Autowired.class, MyAutowired.class, CustomAutowired.class));
        beanPostProcessor.setAutowiredAnnotationTypes(types);
        return beanPostProcessor;
    }
    public static void main(String[] args)
    {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册当前类,主要目的是获取@Bean
        applicationContext.register(Demo.class);
        //启动应用上下文
        applicationContext.refresh();
        Demo bean = applicationContext.getBean(Demo.class);
        System.out.println("user对象:"+bean.user);
        System.out.println("myUser对象:"+bean.myUser);
        System.out.println("自定义对象:"+bean.customAutowiredUser);
        applicationContext.close();
    }
}

结果

Connected to the target VM, address: '127.0.0.1:52324', transport: 'socket'
user对象:User{id=1, name='Java面试教程'}
myUser对象:User{id=1, name='Java面试教程'}
自定义对象:User{id=1, name='Java面试教程'}
Disconnected from the target VM, address: '127.0.0.1:52324', transport: 'socket'

结束语

我们刚刚通过了 拓展@Autowired注解 以及 复用AutowiredAnnotationBeanPostProcessor这个API 两种方式来实现替代@Autowired注解,虽然内容简单,但是却通过了AutowiredAnnotationBeanPostProcessor向大家揭晓了为什么Autowired可以达到依赖注入的原因。

相关文章
|
2天前
|
云安全 人工智能 算法
以“AI对抗AI”,阿里云验证码进入2.0时代
三层立体防护,用大模型打赢人机攻防战
1292 1
|
9天前
|
编解码 人工智能 自然语言处理
⚽阿里云百炼通义万相 2.6 视频生成玩法手册
通义万相Wan 2.6是全球首个支持角色扮演的AI视频生成模型,可基于参考视频形象与音色生成多角色合拍、多镜头叙事的15秒长视频,实现声画同步、智能分镜,适用于影视创作、营销展示等场景。
698 4
|
2天前
|
机器学习/深度学习 安全 API
MAI-UI 开源:通用 GUI 智能体基座登顶 SOTA!
MAI-UI是通义实验室推出的全尺寸GUI智能体基座模型,原生集成用户交互、MCP工具调用与端云协同能力。支持跨App操作、模糊语义理解与主动提问澄清,通过大规模在线强化学习实现复杂任务自动化,在出行、办公等高频场景中表现卓越,已登顶ScreenSpot-Pro、MobileWorld等多项SOTA评测。
544 2
|
3天前
|
人工智能 Rust 运维
这个神器让你白嫖ClaudeOpus 4.5,Gemini 3!还能接Claude Code等任意平台
加我进AI讨论学习群,公众号右下角“联系方式”文末有老金的 开源知识库地址·全免费
|
2天前
|
存储 弹性计算 安全
阿里云服务器4核8G收费标准和活动价格参考:u2a实例898.20元起,计算型c9a3459.05元起
现在租用阿里云服务器4核8G价格是多少?具体价格及配置详情如下:云服务器ECS通用算力型u2a实例,配备4核8G配置、1M带宽及40G ESSD云盘(作为系统盘),其活动价格为898.20元/1年起;此外,ECS计算型c9a实例4核8G配置搭配20G ESSD云盘,活动价格为3459.05元/1年起。在阿里云的当前活动中,4核8G云服务器提供了多种实例规格供用户选择,不同实例规格及带宽的组合将带来不同的优惠价格。本文为大家解析阿里云服务器4核8G配置的实例规格收费标准与最新活动价格情况,以供参考。
234 150
|
9天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:七十、小树成林,聚沙成塔:随机森林与大模型的协同进化
随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并结合它们的预测结果来提高准确性和稳定性。其核心思想包括两个随机性:Bootstrap采样(每棵树使用不同的训练子集)和特征随机选择(每棵树分裂时只考虑部分特征)。这种方法能有效处理大规模高维数据,避免过拟合,并评估特征重要性。随机森林的超参数如树的数量、最大深度等可通过网格搜索优化。该算法兼具强大预测能力和工程化优势,是机器学习中的常用基础模型。
355 164