模拟Spring源码思想,手写源码,理解注解

1、BeanDefinition

package com.csdn.myspring;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class BeanDefinition {private String beanName;private Class beanClass;
}

2、扫描包的工具类MyTools

package com.csdn.myspring;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class MyTools {public static Set<Class<?>> getClasses(String pack) {// 第一个class类的集合Set<Class<?>> classes = new LinkedHashSet<Class<?>>();// 是否循环迭代boolean recursive = true;// 获取包的名字 并进行替换String packageName = pack;String packageDirName = packageName.replace('.', '/');// 定义一个枚举的集合 并进行循环来处理这个目录下的thingsEnumeration<URL> dirs;try {dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);// 循环迭代下去while (dirs.hasMoreElements()) {// 获取下一个元素URL url = dirs.nextElement();// 得到协议的名称String protocol = url.getProtocol();// 如果是以文件的形式保存在服务器上if ("file".equals(protocol)) {// 获取包的物理路径String filePath = URLDecoder.decode(url.getFile(), "UTF-8");// 以文件的方式扫描整个包下的文件 并添加到集合中findClassesInPackageByFile(packageName, filePath, recursive, classes);} else if ("jar".equals(protocol)) {// 如果是jar包文件// 定义一个JarFileSystem.out.println("jar类型的扫描");JarFile jar;try {// 获取jarjar = ((JarURLConnection) url.openConnection()).getJarFile();// 从此jar包 得到一个枚举类Enumeration<JarEntry> entries = jar.entries();findClassesInPackageByJar(packageName, entries, packageDirName, recursive, classes);} catch (IOException e) {// log.error("在扫描用户定义视图时从jar包获取文件出错");e.printStackTrace();}}}} catch (IOException e) {e.printStackTrace();}return classes;}private static void findClassesInPackageByJar(String packageName, Enumeration<JarEntry> entries, String packageDirName, final boolean recursive, Set<Class<?>> classes) {// 同样的进行循环迭代while (entries.hasMoreElements()) {// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件JarEntry entry = entries.nextElement();String name = entry.getName();// 如果是以/开头的if (name.charAt(0) == '/') {// 获取后面的字符串name = name.substring(1);}// 如果前半部分和定义的包名相同if (name.startsWith(packageDirName)) {int idx = name.lastIndexOf('/');// 如果以"/"结尾 是一个包if (idx != -1) {// 获取包名 把"/"替换成"."packageName = name.substring(0, idx).replace('/', '.');}// 如果可以迭代下去 并且是一个包if ((idx != -1) || recursive) {// 如果是一个.class文件 而且不是目录if (name.endsWith(".class") && !entry.isDirectory()) {// 去掉后面的".class" 获取真正的类名String className = name.substring(packageName.length() + 1, name.length() - 6);try {// 添加到classesclasses.add(Class.forName(packageName + '.' + className));} catch (ClassNotFoundException e) {// .error("添加用户自定义视图类错误 找不到此类的.class文件");e.printStackTrace();}}}}}}private static void findClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) {// 获取此包的目录 建立一个FileFile dir = new File(packagePath);// 如果不存在或者 也不是目录就直接返回if (!dir.exists() || !dir.isDirectory()) {// log.warn("用户定义包名 " + packageName + " 下没有任何文件");return;}// 如果存在 就获取包下的所有文件 包括目录File[] dirfiles = dir.listFiles(// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)(file)-> {return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));});// 循环所有文件for (File file : dirfiles) {// 如果是目录 则继续扫描if (file.isDirectory()) {findClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);} else {// 如果是java类文件 去掉后面的.class 只留下类名String className = file.getName().substring(0, file.getName().length() - 6);try {// 添加到集合中去// classes.add(Class.forName(packageName + '.' +// className));// 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));} catch (ClassNotFoundException e) {// log.error("添加用户自定义视图类错误 找不到此类的.class文件");e.printStackTrace();}}}}
}

3、MyAnnotationConfigApplicationContext

package com.csdn.myspring;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class MyAnnotationConfigApplicationContext {private Map<String, Object> ioc = new HashMap<>();public MyAnnotationConfigApplicationContext() {}public MyAnnotationConfigApplicationContext(String pack) {//遍历包,找到目标类(原材料)Set<BeanDefinition> beanDefinitions = findBeanDefinitions(pack);//根据原材料获取beancreateObject(beanDefinitions);//自动装配autowireObject(beanDefinitions);}public void autowireObject(Set<BeanDefinition> beanDefinitions) {Iterator<BeanDefinition> iterator = beanDefinitions.iterator();while (iterator.hasNext()) {BeanDefinition beanDefinition = iterator.next();Class clazz = beanDefinition.getBeanClass();Field[] declaredFields = clazz.getDeclaredFields();for (Field declaredField : declaredFields) {Autowired annotation = declaredField.getAnnotation(Autowired.class);if (annotation!=null) {Qualifier qualifier = declaredField.getAnnotation(Qualifier.class);if (qualifier!=null) {try {String beanName = qualifier.value();Object bean = getBean(beanName);String fieldName = declaredField.getName();String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);Method method = clazz.getMethod(methodName, declaredField.getType());Object object = getBean(beanDefinition.getBeanName());method.invoke(object, bean);} catch (NoSuchMethodException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}Object object = getBean(beanDefinition.getBeanName());}}}}}public Set<BeanDefinition> findBeanDefinitions(String pack) {//获取包下的所有类Set<Class<?>> classes = MyTools.getClasses(pack);Iterator<Class<?>> iterator = classes.iterator();Set<BeanDefinition> beanDefinitions = new HashSet<>();while (iterator.hasNext()) {//2、遍历这些类,找到添加了注解的类Class<?> clazz = iterator.next();Component componentAnnotation = clazz.getAnnotation(Component.class);if (componentAnnotation != null) {//获取Component注解的值String beanName = componentAnnotation.value();if ("".equals(beanName)) {//获取类名首字母小写String className = clazz.getName().replaceAll(clazz.getPackage().getName() + ".", "");beanName = className.substring(0, 1).toLowerCase() + className.substring(1);}//3、将这些类封装成BeanDefinition,装载到集合中beanDefinitions.add(new BeanDefinition(beanName, clazz));}}return beanDefinitions;}public void createObject(Set<BeanDefinition> beanDefinitions) {Iterator<BeanDefinition> iterator = beanDefinitions.iterator();while (iterator.hasNext()) {BeanDefinition beanDefinition = iterator.next();Class clazz = beanDefinition.getBeanClass();String beanName = beanDefinition.getBeanName();try {//创建对象Object object = clazz.getConstructor().newInstance();//完成属性的赋值Field[] declaredFields = clazz.getDeclaredFields();for (Field declaredField : declaredFields) {Value valueAnnotation = declaredField.getAnnotation(Value.class);if (valueAnnotation!=null) {String value = valueAnnotation.value();String fieldName = declaredField.getName();String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);Method method = clazz.getMethod(methodName, declaredField.getType());//完成数据类型转换Object val = null;switch (declaredField.getType().getName()) {case "java.lang.Integer" -> val=Integer.parseInt(value);case "java.lang.String"-> val = value;case "java.lang.Float"-> Float.parseFloat(value);}method.invoke(object, val);}}//存入缓存ioc.put(beanName, object);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);} catch (NoSuchMethodException e) {throw new RuntimeException(e);}}}public Object getBean(String beanName) {return ioc.get(beanName);}public static void main(String[] args) {MyAnnotationConfigApplicationContext myAnnotationConfigApplicationContext = new MyAnnotationConfigApplicationContext("com.csdn.myspring");Person bean = (Person) myAnnotationConfigApplicationContext.getBean("b");System.out.println(bean.getName());}
}

4、@Component

package com.csdn.myspring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {String value() default "";
}

5、@Value

package com.csdn.myspring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Value {String value();
}

6、@Autowired

package com.csdn.myspring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
}

7、@Qualifier

package com.csdn.myspring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Qualifier {String value();
}

@Qualifier是一个Spring框架的注解,用于标识一个Bean的特定实例。当有多个Bean实现了同一接口或类时,@Qualifier可以指定要使用的实例。

通常情况下,Spring框架根据类型来自动装配依赖,但如果有多个 Bean 与依赖的类型匹配,则会产生歧义。这时就需要使用 @Qualifier 来指定具体匹配的 Bean。

例如:

public interface Animal {// ...
}@Component
@Qualifier("cat")
public class Cat implements Animal {// ...
}@Component
@Qualifier("dog")
public class Dog implements Animal {// ...
}@Service
public class AnimalService {@Autowired@Qualifier("cat")private Animal animal;// ...
}

在这个例子中,AnimalService 类需要注入一个 Animal 接口的实例,但有两个实现类 Cat 和 Dog。使用 @Qualifier 标记 Cat 和 Dog 实例,然后在 AnimalService 中使用 @Autowired 和 @Qualifier("cat") 标记,就可以明确指定注入 Cat 实例了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/161761.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

@Scheduled注解 定时任务讲解

用于在Java Spring框架中定时执行特定任务的注解 Scheduled&#xff0c;它能够指定方法在特定时间间隔或特定时间点执行。默认参数是cron&#xff0c;cron参数被用来定义一个Cron表达式&#xff0c;它代表了任务执行的时间规则 参数如下 Cron 这是是一种时间表达式&#xff…

【应用程序启动过程-三种加载控制器的方式-上午内容复习 Objective-C语言】

一、我们先来回忆一下,上午所有内容 1.首先呢,我们先说的是这个“应用程序启动过程”, 应用程序启动过程里面,有三方面内容 1)UIApplication对象介绍 2)AppDelegate对象介绍 3)应用程序启动过程 现在不知道大家对这个应用程序启动过程有印象吗, 2.首先,这个UIAp…

MySQL数据库时间计算的用法

今天给大家分享如何通过MySQL内置函数实现时间的转换和计算&#xff0c;在工作当中&#xff0c;测试人员经常需要查询数据库表的日期时间&#xff0c;但发现开发人员存入数据库表的形式都是时间戳形式&#xff0c;不利于测试人员查看&#xff0c;测试人员只能利用工具对时间戳进…

【 顺序表经典算法—移除元素和合并两个有序数组】

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 目录 前言 经典算法OJ题1&#xff1a; 移除元素 解法一、逐个判断 解法二、双指针覆盖 经典算法OJ题2&#xff1a; 合并两个有序数组 OJ题分为两个类型&#xff1a; 总结 前言…

MAX/MSP SDK学习07:list传递

实现自定义Obejct&#xff0c;要求将传入的一组数据100后传出。 #include "ext.h" #include "ext_obex.h" typedef struct _listTrans {t_object ob;void* outLet;t_atom* fArr;long listNum;} t_listTrans;void* listTrans_new(t_symbol* s, long arg…

14.Python 模块

目录 1. 使用模块2. 使用包3. 常用模块3.1 日期和时间3.2 伪随机数3.3 摘要算法3.4 JSON 处理3.5 图像处理 模块是Python用来组织代码的一种方法&#xff0c;包是Python用来组织模块的一种方法。 1. 使用模块 Python 把能够相互包含&#xff0c;且有组织的代码段称为模块&…

.NET面试题1

1.什么是C#&#xff1f; C#&#xff08;读作"C sharp"&#xff09;是一种通用的、面向对象的编程语言&#xff0c;由Microsoft开发。它是一种静态类型语言&#xff0c;支持强类型检查和面向对象编程&#xff08;OOP&#xff09;的概念。C#主要用于开发Windows应用程序…

Bug等级划分

Bug是指在程序或系统中存在的错误、缺陷或异常&#xff0c;是由于编码错误、设计问题、逻辑错误或其他因素导致的。 常见的Bug分类方法 功能性Bug与软件的功能有关&#xff0c;软件无法正常工作、功能与需求不符或功能执行不正确。 用户界面Bug与软件的用户界面有关&#xff…

Unity中Shader双向反射分布函数BRDF

文章目录 前言一、渲染方程二、什么是BxDF1、BSSRDF2、BRDF3、BTDF4、BSDF 三、迪士尼原则的BRDF四、迪士尼原则的BRDF的参数五、在Unity中看一下默认Shader的这些参数六、在这里记录一下使用 Blender 和 SubstancePainter 的流程1、在Blender中导出模型为 .obj 格式2、在Subst…

Android WMS—— Surace管理 (二十)

WMS 负责创建 Surface 以及对 Surface 的摆放工作,之后将 Surface 提交给SurfaceFlinger 进行合并。在 App 层也创建了一个 Surface 对象,但是那个是空对象,用于 WMS 的填充。 一、Surface的创建 首先 APP 层在 ViewRootImpl 的 relayoutWindow() 方法中发起创建任务。 1、…

Go 实现网络代理

使用 Go 语言开发网络代理服务可以通过以下步骤完成。这里&#xff0c;我们将使用 golang.org/x/net/proxy 包来创建一个简单的 SOCKS5 代理服务作为示例。 步骤 1. 安装 golang.org/x/net/proxy 包 使用以下命令安装 golang.org/x/net 包&#xff0c;该包包含 proxy 子包&am…

天软特色因子看板 (2023.11 第12期)

该因子看板跟踪天软特色因子A05006(近一月单笔流入流出金额之比(%)&#xff0c;该因子为近一个月单笔流入流出金额之比(%)均值因子&#xff0c;用以刻画在 市场日内分时成交中流入、流出成交金额的差异性特点&#xff0c;发掘市场主力资金的作用机制。 今日为该因子跟踪第12期&…

expect脚本在自动化部署中的具体应用案例

#expect脚本在自动化部署中的具体应用 expect脚本是一个非常好的交互式应用脚本&#xff0c;在自动化部署中&#xff0c;可以使用这个脚本来实现全自动的自动化部署。下面是一些具体的应用案例。 场景一&#xff1a;自动安装mysql 可以使用expect脚本来实现mysql自动安装&…

Windows平台Unity下实现camera场景推送RTMP|轻量级RTSP服务|实时录像

技术背景 我们在对接Unity平台camera场景采集的时候&#xff0c;除了常规的RTMP推送、录像外&#xff0c;还有一些开发者&#xff0c;需要能实现轻量级RTSP服务&#xff0c;对外提供个拉流的RTSP URL。 目前我们在Windows平台Unity下数据源可采集到以下部分&#xff1a; 采集…

@PostConstruct虽好,请勿乱用

1.问题说明 在日常的业务开发中&#xff0c;有时会利用PostConstruct在容器启动时执行一些任务。例如&#xff1a; PostConstruct public void init(){System.out.println("service 初始化..............."); }一般情况这没什么问题&#xff0c;但最近一个同事在做…

ui5使用echart

相关的代码已经发布到github上。 展示下相关的实现功能 1、柱状图-1 2、柱状图-2 3.折线图 4.饼状图 如何使用&#xff1a; 使用git clone项目到本地 git clone https://github.com/linhuang0405/com.joker.Zechart找到index.html。在vscode里右键选择Open with Live Serve…

1

【任务 1】私有云服务搭建[10 分] 【题目 1】基础环境配置[0.5 分] 【题目 2】Yum 源配置[0.5 分] 【题目 3】配置无秘钥 ssh[0.5 分] 【题目 4】基础安装[0.5 分] 【题目 5】数据库安装与调优[0.5 分] 【题目 6】Keystone 服务安装与使用[0.5 分] 【题目 7】Glance 安装与使用…

BLE通用广播包

文章目录 1、蓝牙广播数据格式2、扫描响应数据 1、蓝牙广播数据格式 蓝牙广播包的最大长度是37个字节&#xff0c;其中设备地址占用了6个字节&#xff0c;只有31个字节是可用的。这31个可用的字节又按照一定的格式来组织&#xff0c;被分割为n个AD Structure。如下图所示&…

npm命令

node -v --查看版本 npm install --安装npm npm config get registry --查看npm当前镜像 npm config set registry https://registry.npmmirror.com --设置淘宝镜像 npm版本管理工具

VS Code 如何搭建C/C++环境

目录 一、VS Code是什么&#xff1f; 二、VS Code下载和安装 2.1下载 2.2安装 2.3环境介绍 三、Vs Code配置C/C环境 3.1下载和配置MinGW-w64编译器套件 3.1.1下载 3.1.2配置 一、VS Code是什么&#xff1f; 跨平台&#xff0c;免费且开源的现代轻量级代码编辑器 Vis…