Spring学习:手写简单实现Spring的IOC功能(简单实现依赖注入以及单例多例注解)

零、创建Maven工程

选择quickstart进行创建即可,除了测试类无需引入其他jar包

坐标只需引入junit即可 ,方便后续测试

一、IOC主要部分代码

容器构造器部分代码,为了实现方便,未对扫描包的字节码文件做递归扫描,只扫描一层,后续可改为递归扫描包内字节码文件。

Spring的IOC容器有一个重要方法:getBean方法,此方法利用的beanDefinition对象在IOC初始化过程中进行构建,方便getBean调用,减少其代码量。

扫包过程中获取到的单例池对象在创建完毕后再逐一放入singletonObjMap中。

package org.example.service;

import org.example.spring.*;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author bilibilidick
 * @version 2022 06
 * @date 2022/6/27 23:08
 */

public class MyApplicationContext {

    // 利用哈希表保存beanDefinition
    private final ConcurrentHashMap<String, BeanDefinition> concurrentHashMap = new ConcurrentHashMap<>();
    // 单例池
    private final ConcurrentHashMap<String, Object> singletonBeanMap = new ConcurrentHashMap<>();

    public MyApplicationContext(AppConfig config) {
        // todo 获取到config类上的componentscan注解中的值以扫描字节码文件名
        if (config.getClass().isAnnotationPresent(ComponentScan.class)) {
            // todo 获取注解信息
            ComponentScan annotation = config.getClass().getAnnotation(ComponentScan.class);
            String scanPath = annotation.value().replace(".", "/");
            // todo 获取字节码文件路径
            URL resource = config.getClass().getClassLoader().getResource(scanPath);
            // todo 将获取到的URL转换为File类对象
            File file = new File(resource.getFile());
            // todo 检查此file对象是否为文件夹,若是,则遍历文件夹,按理说应递归获取所有文件,在这里只获取一层
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                String sPath;
                String scopeValue;
                BeanDefinition beanDefinition;
                Class<?> clazz;
                String beanName;
                // todo 遍历每个字节码文件,将其路径中的限定名称提取出来
                for (File path : files) {
                    if ((sPath = path.getAbsolutePath()).endsWith(".class")) {
                        sPath = sPath.substring(sPath.indexOf("org"), sPath.indexOf(".class")).replace("\\", ".");
                        try {
                            clazz = config.getClass().getClassLoader().loadClass(sPath);
                            if (clazz.isAnnotationPresent(Component.class)) {
                                // todo 放入到BeanDefinition类中,方便createBean方法构造Bean
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    scopeValue = clazz.getAnnotation(Scope.class).value();
                                    if ("singleton".equals(scopeValue)) {
                                        beanDefinition = new BeanDefinition(clazz, "singleton");
                                    } else {
                                        beanDefinition = new BeanDefinition(clazz, "prototype");
                                    }
                                } else {
                                    beanDefinition = new BeanDefinition(clazz, "singleton");
                                }
                                beanName = clazz.getAnnotation(Component.class).value();
                                if ("".equals(beanName)) {
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }
                                concurrentHashMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }


                    }
                }
                // todo 初始化IOC容器
                concurrentHashMap.forEach((name, type) -> {
                    if ("singleton".equals(type.getScope())) {
                        singletonBeanMap.put(name, createBean(type));
                    }
                });
            }
        }
    }

    public Object createBean(BeanDefinition beanDefinition) {
        Class type = beanDefinition.getType();
        Object instance = null;
        try {
            instance = type.newInstance();
            Field[] declaredFields = type.getDeclaredFields();
            for (Field field : declaredFields) {
                if (field.isAnnotationPresent(AutoWired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return instance;
    }

    public Object getBean(String name) {
        // todo 输入对象名称返回IOC中的Bean
        if (!concurrentHashMap.containsKey(name)) throw new NullPointerException();
        else {
            BeanDefinition beanDefinition = concurrentHashMap.get(name);
            if ("singleton".equals(beanDefinition.getScope())) {
                Object singleInstance = singletonBeanMap.get(name);
                if (singleInstance == null) {
                    singleInstance = createBean(beanDefinition);
                    singletonBeanMap.put(name, singleInstance);
                }
                return singleInstance;
            } else return createBean(beanDefinition);
        }
    }


}

BeanDefinition类

package org.example.spring;

/**
 * @author bilibilidick
 * @version 2022 06
 * @date 2022/6/27 23:35
 */

public class BeanDefinition {
    private Class type;

    private String scope;

    public BeanDefinition(Class type, String scope) {
        this.type = type;
        this.scope = scope;
    }

    public Class getType() {
        return type;
    }

    public void setType(Class type) {
        this.type = type;
    }

    public String getScope() {
        return scope;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }
}

二、注解实现

@ComponentScan注解,用来设置Spring的扫包路径

package com.xiejianjun.spring;

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 ComponentScan {

    String value() default "";

}

@Component注解,用来表明需放入beanDefinition的类对象

package com.xiejianjun.spring;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Component {

    String value() default "";

}

@Scope注解,用来声明此对象是单例还是多例,默认值为单例

package com.xiejianjun.spring;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Scope {

    String value() default "singleton";

}

@AutoWired注解,用来实现依赖注入

package com.xiejianjun.spring;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoWired {
}

三、测试IOC功能

创建AppConfig配置类

package org.example.service;

import org.example.spring.ComponentScan;

/**
 * @author bilibilidick
 * @version 2022 06
 * @date 2022/6/27 23:09
 */
@ComponentScan("org.example.service")
public class AppConfig {
}

创建OrderService类

package org.example.service;

import org.example.spring.Component;

/**
 * @author bilibilidick
 * @version 2022 06
 * @date 2022/6/28 0:33
 */
@Component
public class OrderService {
}

创建UserService类

package org.example.service;

import org.example.spring.AutoWired;
import org.example.spring.Component;

/**
 * @author bilibilidick
 * @version 2022 06
 * @date 2022/6/27 23:09
 */
@Component
public class UserService {
    @AutoWired
    private OrderService orderService;

    public void test() {
        System.out.println(orderService);
    }

}

利用ApplicationContext创建UserService的对象,调用UserService的test方法

package org.example;

import static org.junit.Assert.assertTrue;

import org.example.service.AppConfig;
import org.example.service.MyApplicationContext;
import org.example.service.UserService;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest 
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        MyApplicationContext myApplicationContext = new MyApplicationContext(new AppConfig());
        UserService userService = (UserService) myApplicationContext.getBean("userService");
        UserService userService1 = (UserService) myApplicationContext.getBean("userService");
        UserService userService2 = (UserService) myApplicationContext.getBean("userService");
        UserService userService3 = (UserService) myApplicationContext.getBean("userService");
        UserService userService4 = (UserService) myApplicationContext.getBean("userService");
        System.out.println(userService1);
        System.out.println(userService2);
        System.out.println(userService3);
        System.out.println(userService4);
        userService.test();
    }
}

输出结果,可以看到已实现UserService中对于OrderService依赖的注入,并且从容器获取到的对象在Scope默认值为单例情况下获取到的都是同一个对象

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值