爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      根据java反射-手写springIoC

      首页 知识中心 其他 文章详情页

      根据java反射-手写springIoC

      2023-07-26 08:00:33 阅读次数:422

      java,jvm

      我们都知道,Spring框架的IOC是基于Java反射机制实现的,下面我们先回顾一下java反射。

      回顾Java反射

      Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。简单来说,反射机制指的是程序在运行时能够获取自身的信息。

      要想解剖一个类,必须先要获取到该类的Class对象。而剖析一个类或用反射解决具体的问题就是使用相关API (1)java.lang.Class(2)java.lang.reflect,所以,Class对象是反射的根源。

      自定义类

      public class Car {
          //属性
          private String name;
          private int age;
          private String color;
      
          //无参数构造
          public Car() {
          }
      
          //有参数构造
          public Car(String name, int age, String color) {
              this.name = name;
              this.age = age;
              this.color = color;
          }
      
          //普通方法
          private void run() {
              System.out.println("私有方法-run.....");
          }
      
          //get和set方法
          public String getName() {
              return name;
          }
          public void setName(String name) {
              this.name = name;
          }
          public int getAge() {
              return age;
          }
          public void setAge(int age) {
              this.age = age;
          }
          public String getColor() {
              return color;
          }
          public void setColor(String color) {
              this.color = color;
          }
      
          @Override
          public String toString() {
              return "Car{" +
                      "name='" + name + '\'' +
                      ", age=" + age +
                      ", color='" + color + '\'' +
                      '}';
          }
      }
      
      

      测试类

      public class TestCar {
          /**
           * //1、获取Class对象多种方式
           *
           * @throws ClassNotFoundException
           * @throws NoSuchMethodException
           * @throws InvocationTargetException
           * @throws InstantiationException
           * @throws IllegalAccessException
           */
          @Test
          public void test01() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
              //1 类名.class
              Class clazz1 = Car.class;
      
              //2 对象.getClass()
              Class clazz2 = new Car().getClass();
      
              //3 Class.forName("全路径")
              Class clazz3 = Class.forName("com.zhubayi.reflect.Car");
      
              //实例化
              Car car = (Car) clazz3.getConstructor().newInstance();
              System.out.println(car);
          }
      
          /**
           * 获取构造方法
           */
          @Test
          public void test02() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
              Class<Car> clazz = Car.class;
              // getConstructors()获取所有public的构造方法
              //Constructor[] constructors = clazz.getConstructors();
              // getDeclaredConstructors()获取所有的构造方法public  private
              Constructor[] constructors = clazz.getDeclaredConstructors();
              for (Constructor c : constructors) {
                  System.out.println("方法名称:" + c.getName() + " 参数个数:" + c.getParameterCount());
              }
              //指定有参数构造创建对象
              //1 构造public
      //        Constructor c1 = clazz.getConstructor(String.class, int.class, String.class);
      //        Car car1 = (Car)c1.newInstance("夏利", 10, "红色");
      //        System.out.println(car1);
      
              //2 构造private
              Constructor c2 = clazz.getDeclaredConstructor(String.class, int.class, String.class);
              c2.setAccessible(true);
              Car car2 = (Car) c2.newInstance("捷达", 15, "白色");
              System.out.println(car2);
          }
      
          //3、获取属性
          @Test
          public void test03() throws Exception {
              Class clazz = Car.class;
              Car car = (Car) clazz.getDeclaredConstructor().newInstance();
              //获取所有public属性
              //Field[] fields = clazz.getFields();
              //获取所有属性(包含私有属性)
              Field[] fields = clazz.getDeclaredFields();
              for (Field field : fields) {
                  if (field.getName().equals("name")) {
                      //设置允许访问
                      field.setAccessible(true);
                      field.set(car, "五菱宏光");
                      System.out.println(car);
                  }
                  System.out.println(field.getName());
              }
          }
      
          //4、获取方法
          @Test
          public void test04() throws Exception {
              Car car = new Car("奔驰", 10, "黑色");
              Class clazz = car.getClass();
              //1 public方法
              Method[] methods = clazz.getMethods();
              for (Method m1 : methods) {
                  //System.out.println(m1.getName());
                  //执行方法 toString
                  if (m1.getName().equals("toString")) {
                      String invoke = (String) m1.invoke(car);
                      //System.out.println("toString执行了:"+invoke);
                  }
              }
              //2 private方法
              Method[] methodsAll = clazz.getDeclaredMethods();
              for (Method m : methodsAll) {
                  //执行方法 run
                  if (m.getName().equals("run")) {
                      m.setAccessible(true);
                      m.invoke(car);
                  }
              }
      
          }
      }
      

      实现Spring的IoC

      我们知道,IoC(控制反转)和DI(依赖注入)是Spring里面核心的东西,那么,我们如何自己手写出这样的代码呢?下面我们就一步一步写出Spring框架最核心的部分。

      添加依赖

      <dependencies>
          <!--junit5测试-->
          <dependency>
              <groupId>org.junit.jupiter</groupId>
              <artifactId>junit-jupiter-api</artifactId>
              <version>5.3.1</version>
          </dependency>
      </dependencies>
      

      定义注解,我们通过注解的形式加载bean与实现依赖注入

      bean注解

      package com.zhubayi.spring.core.annotation;
      
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      
      /**
       * @author zhubayi
       * @Description
       */
      @Target(ElementType.TYPE)//class interface
      @Retention(RetentionPolicy.RUNTIME)
      public @interface Bean {
      
      }
      
      

      依赖注入注解

      package com.zhubayi.spring.core.annotation;
      
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      
      /**
       * @author zhubayi
       * @Description
       */
      @Target({ElementType.FIELD})
      @Retention(RetentionPolicy.RUNTIME)
      public @interface Di {
      
      }
      
      

      说明:上面两个注解可以随意取名

      准备测试需要的bean

      创建UserDao接口

      package com.zhubayi.spring6.test.dao;
      
      /**
       * @author zhubayi
       * @Description
       */
      public interface UserDao {
          void print();
      }
      
      

      创建UserDaoImpl实现

      package com.zhubayi.spring6.test.dao.impl;
      
      import com.zhubayi.spring.core.annotation.Bean;
      import com.zhubayi.spring6.test.dao.UserDao;
      
      /**
       * @author zhubayi
       * @Description
       */
      @Bean
      public class UserDaoImpl implements UserDao {
          @Override
          public void print() {
              System.out.println("Dao方法执行成功!");
          }
      }
      
      

      创建UserService接口

      package com.zhubayi.spring6.test.service;
      
      /**
       * @author zhubayi
       * @Description
       */
      public interface UserService {
          void out();
      }
      
      

      创建UserServiceImpl实现类

      package com.zhubayi.spring6.test.service.impl;
      
      import com.zhubayi.spring.core.annotation.Bean;
      import com.zhubayi.spring.core.annotation.Di;
      import com.zhubayi.spring6.test.dao.UserDao;
      import com.zhubayi.spring6.test.service.UserService;
      
      /**
       * @author zhubayi
       * @Description
       */
      @Bean
      public class UserServiceImpl implements UserService {
          @Override
          public void out() {
              System.out.println("Service层执行结束");
          }
      }
      
      

      定义bean容器接口

      package com.zhubayi.spring.core;
      
      /**
       * @author zhubayi
       * @Description
       */
      public interface ApplicationContext {
          /**
           * 得到bean
           *
           * @param clazz clazz
           * @return {@link Object}
           */
          Object getBean(Class clazz);
      }
      
      

      编写注解bean容器接口实现

      AnnotationApplicationContext基于注解扫描bean

      package com.zhubayi.spring.core;
      
      import java.util.HashMap;
      
      public class AnnotationApplicationContext implements ApplicationContext {
      
          //存储bean的容器
          private HashMap<Class, Object> beanFactory = new HashMap<>();
      
          @Override
          public Object getBean(Class clazz) {
              return beanFactory.get(clazz);
          }
      
          /**
           * 根据包扫描加载bean
           * @param basePackage
           */
          public AnnotationApplicationContext(String basePackage) {
              
          }
      }
      

      编写扫描bean逻辑

      我们通过构造方法传入包的base路径,扫描被@Bean注解的java对象,完整代码如下:

      package com.zhuabyi.spring.core;
      
      import com.atguigu.spring.core.annotation.Bean;
      
      import java.io.File;
      import java.util.HashMap;
      
      public class AnnotationApplicationContext implements ApplicationContext {
      
          //存储bean的容器
          private HashMap<Class, Object> beanFactory = new HashMap<>();
          private static String rootPath;
      
          @Override
          public Object getBean(Class clazz) {
              return beanFactory.get(clazz);
          }
      
          /**
           * 根据包扫描加载bean
           * @param basePackage
           */
          public AnnotationApplicationContext(String basePackage) {
             try {
                  //把.替换成\\
                  String packageDirName = basePackage.replaceAll("\\.", "\\\\");
                  Enumeration<URL> dirs =Thread.currentThread().getContextClassLoader().getResources(packageDirName);
                  while (dirs.hasMoreElements()) {
                      URL url = dirs.nextElement();
                      String filePath = URLDecoder.decode(url.getFile(),"utf-8");
                      rootPath = filePath.substring(0, filePath.length()-packageDirName.length());
                      loadBean(new File(filePath));
                  }
      
              } catch (Exception e) {
                  throw new RuntimeException(e);
              }
          }
      
          private  void loadBean(File fileParent) {
              if (fileParent.isDirectory()) {
                  File[] childrenFiles = fileParent.listFiles();
                  if(childrenFiles == null || childrenFiles.length == 0){
                      return;
                  }
                  for (File child : childrenFiles) {
                      if (child.isDirectory()) {
                          //如果是个文件夹就继续调用该方法,使用了递归
                          loadBean(child);
                      } else {
                          //通过文件路径转变成全类名,第一步把绝对路径部分去掉
                          String pathWithClass = child.getAbsolutePath().substring(rootPath.length() - 1);
                          //选中class文件
                          if (pathWithClass.contains(".class")) {
                              //    com.xinzhi.dao.UserDao
                              //去掉.class后缀,并且把 \ 替换成 .
                              String fullName = pathWithClass.replaceAll("\\\\", ".").replace(".class", "");
                              try {
                                  Class<?> aClass = Class.forName(fullName);
                                  //把非接口的类实例化放在map中
                                  if(!aClass.isInterface()){
                                      Bean annotation = aClass.getAnnotation(Bean.class);
                                      if(annotation != null){
                                          Object instance = aClass.newInstance();
                                          //判断一下有没有接口
                                          if(aClass.getInterfaces().length > 0) {
                                              //如果有接口把接口的class当成key,实例对象当成value
                                              System.out.println("正在加载【"+ aClass.getInterfaces()[0] +"】,实例对象是:" + instance.getClass().getName());
                                              beanFactory.put(aClass.getInterfaces()[0], instance);
                                          }else{
                                              //如果没有接口把自己的class当成key,自己实例对象当成value
                                              System.out.println("正在加载【"+ aClass.getName() +"】,实例对象是:" + instance.getClass().getName());
                                              beanFactory.put(aClass, instance);
                                          }
                                      }
                                  }
                              } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                                  e.printStackTrace();
                              }
                          }
                      }
                  }
              }
          }
      
      }
      

      java类标识Bean注解

      @Bean
      public class UserServiceImpl implements UserService
      
      @Bean
      public class UserDaoImpl implements UserDao 
      

      测试

      package com.zhubayi.spring;
      
      import com.zhubayi.spring.core.AnnotationApplicationContext;
      import com.zhubayi.spring.core.ApplicationContext;
      import com.zhubayi.spring6.test.service.UserService;
      import org.junit.jupiter.api.Test;
      
      /**
       * @author zhubayi
       * @Description
       */
      public class SpringIcoTest {
          @Test
          public void testIoc() {
              ApplicationContext applicationContext = new AnnotationApplicationContext("com.zhubayi.spring6.test");
              UserService userService = (UserService)applicationContext.getBean(UserService.class);
              userService.out();
              System.out.println("run success");
          }
        }
      

      结果

      正在加载【interface com.zhubayi.spring6.test.dao.UserDao】,实例对象是:com.zhubayi.spring6.test.dao.impl.UserDaoImpl
      正在加载【interface com.zhubayi.spring6.test.service.UserService】,实例对象是:com.zhubayi.spring6.test.service.impl.UserServiceImpl
      Service层执行结束
      run success
      

      依赖注入

      只要userDao.print();调用成功,说明就注入成功

      package com.zhubayi.spring6.test.service.impl;
      
      import com.zhubayi.spring.core.annotation.Bean;
      import com.zhubayi.spring.core.annotation.Di;
      import com.zhubayi.spring6.test.dao.UserDao;
      import com.zhubayi.spring6.test.service.UserService;
      
      /**
       * @author zhubayi
       * @Description
       */
      @Bean
      public class UserServiceImpl implements UserService {
          @Di
          private UserDao userDao;
          @Override
          public void out() {
              userDao.print();
              System.out.println("Service层执行结束");
          }
      }
      
      

      根据java反射-手写springIoC
      执行以下代码

      	@Test
          public void testDi() {
              ApplicationContext applicationContext = new AnnotationApplicationContext("com.zhubayi.spring6.test");
              UserService userService = (UserService)applicationContext.getBean(UserService.class);
              userService.out();
              System.out.println("run success");
          }
      

      执行报错

      正在加载【interface com.zhubayi.spring6.test.dao.UserDao】,实例对象是:com.zhubayi.spring6.test.dao.impl.UserDaoImpl
      正在加载【interface com.zhubayi.spring6.test.service.UserService】,实例对象是:com.zhubayi.spring6.test.service.impl.UserServiceImpl
      
      java.lang.NullPointerException: Cannot invoke "com.zhubayi.spring6.test.dao.UserDao.print()" because "this.userDao" is null
      
      	at com.zhubayi.spring6.test.service.impl.UserServiceImpl.out(UserServiceImpl.java:18)
      	at com.zhubayi.spring.SpringIcoTest.testDi(SpringIcoTest.java:24)
      	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
      	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
      	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:515)
      	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
      	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
      	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
      	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
      	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
      	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:105)
      	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)
      	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
      	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:110)
      	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)
      	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
      	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:110)
      	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)
      	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)
      	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
      	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
      	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
      	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
      	at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
      	at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
      	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
      	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
      	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
      	at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
      	at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
      	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
      	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
      	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
      

      说明当前userDao是个空对象

      依赖注入实现

      package com.zhubayi.spring.core;
      
      import com.zhubayi.spring.core.annotation.Bean;
      import com.zhubayi.spring.core.annotation.Di;
      
      import java.io.File;
      import java.lang.reflect.Field;
      import java.net.URL;
      import java.net.URLDecoder;
      import java.util.Enumeration;
      import java.util.HashMap;
      import java.util.Map;
      
      /**
       * @author zhubayi
       * @Description
       */
      public class AnnotationApplicationContext implements ApplicationContext {
          //存储bean的容器
          private Map<Class, Object> beanFactory = new HashMap<>();
          private static String rootPath;
      
          /**
           * 得到bean
           *
           * @param clazz clazz
           * @return {@link Object}
           */
          @Override
          public Object getBean(Class clazz) {
              return beanFactory.get(clazz);
          }
      
          /**
           * 根据包扫描加载bean
           *
           * @param basePackage
           */
          public AnnotationApplicationContext(String basePackage) {
              try {
                  //就是把.替换成\\
                  String packageDirName = basePackage.replaceAll("\\.", "\\\\");
                  Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
                  while (dirs.hasMoreElements()) {
                      URL url = dirs.nextElement();
                      //防止中文乱码
                      String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                      //根路径
                      rootPath = filePath.substring(0, filePath.length() - packageDirName.length());
                      loadBean(new File(filePath));
                  }
      
              } catch (Exception e) {
                  e.printStackTrace();
              }
              //依赖注入
              loadDi();
          }
      
          private void loadBean(File fileParent) {
              //是目录
              if (fileParent.isDirectory()) {
                  File[] childrenFiles = fileParent.listFiles();
                  if (childrenFiles == null || childrenFiles.length == 0) {
                      return;
                  }
                  for (File child : childrenFiles) {
                      if (child.isDirectory()) {
                          //如果是个文件夹就继续调用该方法,使用了递归
                          loadBean(child);
                      } else {
                          //通过文件路径转变成全类名,第一步把绝对路径部分去掉
                          String pathWithClass = child.getAbsolutePath().substring(rootPath.length() - 1);
                          if (pathWithClass.contains(".class")) {
                              //    com.xinzhi.dao.UserDao
                              //去掉.class后缀,并且把 \ 替换成 .
                              String fullName = pathWithClass.replaceAll("\\\\", ".").replace(".class", "");
                              try {
                                  Class<?> aClass = Class.forName(fullName);
                                  //把非接口的类实例化放在map中
                                  if (!aClass.isInterface()) {
                                      Bean annotation = aClass.getAnnotation(Bean.class);
                                      if (annotation != null) {
                                          Object instance = aClass.newInstance();
                                          //判断一下有没有接口
                                          if (aClass.getInterfaces().length > 0) {
                                              //如果有接口把接口的class当成key,实例对象当成value
                                              System.out.println("正在加载【" + aClass.getInterfaces()[0] + "】,实例对象是:" + instance.getClass().getName());
                                              beanFactory.put(aClass.getInterfaces()[0], instance);
                                          } else {
                                              //如果没有接口把自己的class当成key,实例对象当成value
                                              System.out.println("正在加载【" + aClass.getName() + "】,实例对象是:" + instance.getClass().getName());
                                              beanFactory.put(aClass, instance);
                                          }
                                      }
                                  }
                              } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                                  e.printStackTrace();
                              }
                          }
                      }
                  }
              }
          }
      
          private void loadDi() {
              for (Map.Entry<Class, Object> entry : beanFactory.entrySet()) {
                  Object obj = entry.getValue();
                  Class<?> aClass = obj.getClass();
                  Field[] fields = aClass.getDeclaredFields();
                  for (Field field : fields) {
                      Di di = field.getAnnotation(Di.class);
                      if (di != null) {
                          field.setAccessible(true);
                          try {
                              System.out.println("正在给【" + obj.getClass().getName() + "】属性【" + field.getName() + "】注入值【" + beanFactory.get(field.getType()).getClass().getName() + "】");
                              field.set(obj, beanFactory.get(field.getType()));
                          } catch (IllegalAccessException e) {
                              throw new RuntimeException(e);
                          }
                      }
                  }
              }
          }
      
      }
      
      

      再次执行testDi 方法

      正在加载【interface com.zhubayi.spring6.test.dao.UserDao】,实例对象是:com.zhubayi.spring6.test.dao.impl.UserDaoImpl
      正在加载【interface com.zhubayi.spring6.test.service.UserService】,实例对象是:com.zhubayi.spring6.test.service.impl.UserServiceImpl
      正在给【com.zhubayi.spring6.test.service.impl.UserServiceImpl】属性【userDao】注入值【com.zhubayi.spring6.test.dao.impl.UserDaoImpl】
      Dao方法执行成功!
      Service层执行结束
      run success
      

      执行成功,依赖注入成功

      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.csdn.net/qq_44732146/article/details/128852747,作者:胡八一,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:idea main方法执行报错:Command line is too long 解决办法

      下一篇:java读取resources目录下的txt文件

      相关文章

      2025-05-14 10:02:58

      java项目多端数据同步解决方案

      多端数据同步是指在多个设备(例如桌面应用、移动应用、Web应用)之间保持数据的一致性。

      2025-05-14 10:02:58
      java , Spring , WebSocket , 同步 , 数据 , 版本号
      2025-05-14 10:02:58

      java休眠到指定时间怎么写

      java休眠到指定时间怎么写

      2025-05-14 10:02:58
      java , sleep , Thread , util , 方法
      2025-05-13 09:49:12

      Java学习(动态代理的思想详细分析与案例准备)(1)

      Java学习(动态代理的思想详细分析与案例准备)(1)

      2025-05-13 09:49:12
      java , 代理 , 代码 , 对象 , 接口 , 方法 , 需要
      2025-05-09 08:20:32

      基于IDEA的Maven简单工程创建及结构分析

      通过一个 mvn 命令直接让我们创建一个 Maven 的脚手架。

      2025-05-09 08:20:32
      java , Maven , xml , 创建 , 文件 , 文件夹 , 项目
      2025-05-08 09:03:57

      前K个高频元素java

      给定一个非空的整数数组,返回其中出现频率前 前K个高频元素java 高的元素。

      2025-05-08 09:03:57
      java , 元素 , 样例 , 给定
      2025-05-08 09:03:21

      基于java Swing开发的学生成绩管理系统【项目源码+数据库脚本】

      基于java Swing开发的学生成绩管理系统【项目源码+数据库脚本】

      2025-05-08 09:03:21
      java , Swing , 学生 , 源码
      2025-05-08 09:03:21

      java Swing学生成绩管理系统【项目源码+数据库脚本】

      本项目是一套基于java Swing开发的学生成绩管理系统,主要针对计算机相关专业的正在做bishe的学生和需要项目实战练习的Java学习者。

      2025-05-08 09:03:21
      java , 学生 , 成绩 , 数据库 , 源码
      2025-05-07 09:08:08

      java Swing学生选课管理系统【源码+数据库+报告】

      本项目是一套基于java Swing学生选课管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。

      2025-05-07 09:08:08
      java , 学生 , 截图 , 源码
      2025-05-07 09:08:08

      java swing人机对战五子棋(含背景音乐)

      本项目是一套基于java swing的人机对战五子棋系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。

      2025-05-07 09:08:08
      java , 源码
      2025-04-22 09:40:08

      【ETL工具】kettle 程序报错 Javascript error: TypeError: Cannot call method “trim“ of null

      【ETL工具】kettle 程序报错 Javascript error: TypeError: Cannot call method “trim“ of null

      2025-04-22 09:40:08
      java , javascript , org
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5230324

      查看更多

      最新文章

      java休眠到指定时间怎么写

      2025-05-14 10:02:58

      基于IDEA的Maven简单工程创建及结构分析

      2025-05-09 08:20:32

      java中final的用法

      2025-04-11 07:15:54

      使用ZipEntry解压zip文件报错: java.lang.IllegalArgumentException: MALFORMED

      2025-04-09 09:17:07

      总结java中文件拷贝剪切的5种方式-JAVA IO基础总结第五篇

      2025-04-09 09:14:24

      JAVA本地编译运行出现的找不到类名问题

      2025-03-14 09:05:42

      查看更多

      热门文章

      在java正则表达式中为什么要对 . 进行两次的转义操作 (\\.)才表示真正的 .

      2023-05-15 10:01:56

      GC是什么? 为什么要有GC?

      2023-05-10 06:02:16

      axios&spring前后端分离传参规范总结

      2023-05-22 08:09:06

      Jsp Ajax之模拟用户注册

      2022-11-17 12:37:24

      定义一个函数,接收三个参数返回一元二次方程

      2023-02-13 07:59:59

      JAVA基础加强笔记

      2022-11-14 02:56:39

      查看更多

      热门标签

      linux java python javascript 数组 前端 docker Linux vue 函数 shell git 节点 容器 示例
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      Maven的生命周期与插件

      spring boot报错:There is no PasswordEncoder mapped for the id “null“

      fix协议介绍4-心跳

      JDBC的入门

      JVM中的堆

      11.盛最多水的容器

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号