思尐-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天前
|
云安全 监控 安全
|
7天前
|
机器学习/深度学习 人工智能 自然语言处理
Z-Image:冲击体验上限的下一代图像生成模型
通义实验室推出全新文生图模型Z-Image,以6B参数实现“快、稳、轻、准”突破。Turbo版本仅需8步亚秒级生成,支持16GB显存设备,中英双语理解与文字渲染尤为出色,真实感和美学表现媲美国际顶尖模型,被誉为“最值得关注的开源生图模型之一”。
875 5
|
12天前
|
人工智能 Java API
Java 正式进入 Agentic AI 时代:Spring AI Alibaba 1.1 发布背后的技术演进
Spring AI Alibaba 1.1 正式发布,提供极简方式构建企业级AI智能体。基于ReactAgent核心,支持多智能体协作、上下文工程与生产级管控,助力开发者快速打造可靠、可扩展的智能应用。
1083 41
|
9天前
|
机器学习/深度学习 人工智能 数据可视化
1秒生图!6B参数如何“以小博大”生成超真实图像?
Z-Image是6B参数开源图像生成模型,仅需16GB显存即可生成媲美百亿级模型的超真实图像,支持中英双语文本渲染与智能编辑,登顶Hugging Face趋势榜,首日下载破50万。
650 37
|
12天前
|
人工智能 前端开发 算法
大厂CIO独家分享:AI如何重塑开发者未来十年
在 AI 时代,若你还在紧盯代码量、执着于全栈工程师的招聘,或者仅凭技术贡献率来评判价值,执着于业务提效的比例而忽略产研价值,你很可能已经被所谓的“常识”困住了脚步。
717 61
大厂CIO独家分享:AI如何重塑开发者未来十年
|
8天前
|
存储 自然语言处理 测试技术
一行代码,让 Elasticsearch 集群瞬间雪崩——5000W 数据压测下的性能避坑全攻略
本文深入剖析 Elasticsearch 中模糊查询的三大陷阱及性能优化方案。通过5000 万级数据量下做了高压测试,用真实数据复刻事故现场,助力开发者规避“查询雪崩”,为您的业务保驾护航。
452 28
|
16天前
|
数据采集 人工智能 自然语言处理
Meta SAM3开源:让图像分割,听懂你的话
Meta发布并开源SAM 3,首个支持文本或视觉提示的统一图像视频分割模型,可精准分割“红色条纹伞”等开放词汇概念,覆盖400万独特概念,性能达人类水平75%–80%,推动视觉分割新突破。
926 59
Meta SAM3开源:让图像分割,听懂你的话
|
5天前
|
弹性计算 网络协议 Linux
阿里云ECS云服务器详细新手购买流程步骤(图文详解)
新手怎么购买阿里云服务器ECS?今天出一期阿里云服务器ECS自定义购买流程:图文全解析,阿里云服务器ECS购买流程图解,自定义购买ECS的设置选项是最复杂的,以自定义购买云服务器ECS为例,包括付费类型、地域、网络及可用区、实例、镜像、系统盘、数据盘、公网IP、安全组及登录凭证详细设置教程:
204 114