手写Spring之IOC基于注解动态创建对象

在上一篇使用了基于xml文件创建对象的方式实现了IOC,这个是基于注解实现的方式。

废话不多说了,直接看代码!!

上类图

在这里插入图片描述

此次实现不需要导入第三方依赖,先创建自己的注解

在这里插入图片描述

MyComponent注解内容如下
	package com.spring.ioc.ioc_annotation.annotation;

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 表示在运行时有效
 *
 * @interface 表示注解类型
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComponent {
    /**
     * 为此注解定义scope属性
     * @return
     */
    public String scope();
}
MyValue注解内容如下
package com.spring.ioc.ioc_annotation.annotation;

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

/**
 * @rarget 属性表示该注解用在什么位置
 * ElementType.FIELD 表示可作用于枚举 常量上
 * @Retention 表示所定义的注解在何时生效
 * RetentionPolicy.RUNTIME 表示在运行时间有效
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValue {
    /**
     * 定义value属性
     * @return
     */
    public String value();
}

接下来创建实体类,为方便测试,分别创建一个单例对象和一个多例对象(同样的,为节省空间get和set方法我省略掉了)

单例对象
package com.spring.ioc.ioc_annotation.pojo;

import com.spring.ioc.ioc_annotation.annotation.MyComponent;
import com.spring.ioc.ioc_annotation.annotation.MyValue;

@MyComponent(scope = "singleton")
public class SingletonUser {

    @MyValue(value = "1")
    private Integer id;

    @MyValue(value = "冬瓜")
    private String name;

    @MyValue(value = "123456")
    private String password;

    public SingletonUser() {
        System.out.println("无参构造方法执行");
    }

    @Override
    public String toString() {
        return "SingletonUser{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
多例对象
package com.spring.ioc.ioc_annotation.pojo;

import com.spring.ioc.ioc_annotation.annotation.MyComponent;
import com.spring.ioc.ioc_annotation.annotation.MyValue;

@MyComponent(scope = "prototype")
public class PrototypeUser {

    @MyValue(value = "1")
    private Integer id;

    @MyValue(value = "南瓜")
    private String name;

    @MyValue(value = "654321")
    private String password;

    public PrototypeUser() {
        System.out.println("无参构造方法执行");
    }
    @Override
    public String toString() {
        return "PrototypeUser{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

}

基础工作完成,接下来创建核心AnnotationConfigApplicationContext工厂类

在这里插入图片描述

首先在内部定义两个map容器,用于存储对象

package com.spring.ioc.ioc_annotation.applicationContext;

import com.spring.ioc.ioc_annotation.annotation.MyComponent;
import com.spring.ioc.ioc_annotation.annotation.MyValue;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AnnotationConfigApplicationContext工厂类
 * 内部有一个初始化方法,
 * 在创建AnnotationConfigApplicationContext对象时即会扫描指定的包路径,
 * 并加载类定义对象到容器中。
 */
public class AnnotationConfigApplicationContext {
    //定义两个map容器用于存储对象
    //此map容器用于存储类定义对象
    private Map<String, Class<?>> beanDefinationFactory = new HashMap<>();
    //此map容器用于存储单例对象
    private Map<String, Object> singletonbeanFactory = new HashMap<>();
}

定义有参构造方法

   /**
     * 创建构造函数,参数类型为指定要扫描加载的包路径
     * @param packageName 包路径
     */
    public AnnotationConfigApplicationContext(String packageName) {
        scanPky(packageName);
    }

在创建对象初始化时,会调用scanPkg方法扫描指定路径下的文件,所以在此定义该方法:

 /**
     * 扫描指定包,找到包中的文件
     * 对于标准(类上有定义注解的)类文件反射加载创建类定义对象并放在容器中
     *
     * @param pkg
     */
    private void scanPky(final String pkg) {
        //替换包名中的".",将包结构转换为目录结构
        String pkgDir = pkg.replaceAll("\\.", "/");
        //获取目录结构在类路径中的位置(其中url中封装了具体资源的路径)
        URL url = getClass().getClassLoader().getResource(pkgDir);
        //基于这个路径资源(url),构建一个文件对象
        File file = new File(url.getFile());
        //获取此目录中指定标准(以.class结尾)的文件
        //listFiles(new FileFilter)(){ accepr(File file)}
        // 这个方法用于遍历这个文件夹内的所有文件并处理
        File[] fs = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                //获取文件名
                String fName = file.getName();
                //判断该文件是否是目录,是目录则递归进一步扫描其内部文件
                if (file.isDirectory()) {
                    scanPky(pkg + "." + fName);
                } else {
                    //如果不是目录,则判断文件后缀是不是以.class结尾
                    if (fName.endsWith(".class")) {
                        return true;
                    }
                }
                return false;
            }
        });
        //遍历所有符合标准的File文件
        for (File f : fs) {
            //获取文件名
            String fName = f.getName();
            //获取去除.class之后的文件名
            fName = fName.substring(0, fName.lastIndexOf("."));
            //将名字(类名,通常为大写开头)的第一个字母转换为小写(用它作为key存储工厂中)
            String key = String.valueOf(fName.charAt(0)).toLowerCase() + fName.substring(1);
            //创建一个类全名(包名.类名)
            String pkgCls = pkg + "." + fName;
            try {
                //通过反射构建类对象
                Class<?> c = Class.forName(pkgCls);
                //判断这个类上是否有MyComponent注解
                if (c.isAnnotationPresent(MyComponent.class)) {
                    //将类对象存储到map容器中
                    beanDefinationFactory.put(key, c);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

以上为初始方法,接下类写getBean方法

/**
     * 根据传入的bean的id值获取容器中的对象,类型为object
     *
     * @param beanId
     * @return
     */
    public Object getBean(String beanId) {
        //根据传入的id获取类对象
        Class<?> cls = beanDefinationFactory.get(beanId);
        //根据类对象获取其定义的注解
        MyComponent annotation = cls.getAnnotation(MyComponent.class);
        //获取注解scope属性值
        String scope = annotation.scope();
        try {
            //如果scope等于singleton则创建单例对象
            if ("singleton".equals(scope)) {
                //判断容器中是否已有该对象的实例,如果没有就创建一个实例对象放到容器中
                if (singletonbeanFactory.get(beanId) == null) {
                    //创建该反射类的实例对象
                    Object instance = cls.newInstance();
                    //给对象的成员属性赋值
                    setFieldValues(cls, instance);
                    //将该对象存储在单例容器中
                    singletonbeanFactory.put(beanId, instance);
                }
                //根据beanid获取单例对象并返回
                return singletonbeanFactory.get(beanId);
            }
            //如果scope等于prototype,则创建并返回多例对象
            if ("prototype".equals(scope)) {
                //创建该反射类的实例对象
                Object instance = cls.newInstance();
                //给对象的成员属性赋值
                setFieldValues(cls, instance);
                //返回这个对象
                return instance;
            }
            //目前仅支持单例和多例两种创建对象方式
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        //如果遭遇异常则返回null
        return null;
    }
     /**
     * 此为重载方法 根据传入的class对象在内部进行强转 返回传入class对象的类型
     *
     * @param beanId
     * @param c
     * @param <T>
     * @return
     */
    public <T> T getBean(String beanId, Class<T> c) {
        return (T) getBean(beanId);
    }

在getBean方法中用到了为成员属性赋值的方法setFieldValue,内容入下:

   /**
     * 此方法用于为对象的属性赋值
     * 内部是通过获取成员属性上注解的值,在转换类型之后,通过反射为对象赋值
     *
     * @param cls 类定义对象
     * @param obj 要为其赋值的实例对象
     */
    public void setFieldValues(Class<?> cls, Object obj) {
        //获取类中所有的成员属性
        Field[] fields = cls.getDeclaredFields();
        //遍历所有属性
        for (Field field : fields) {
            //如果此属性有MyValue注解修饰,对其进行操作
            if (field.isAnnotationPresent(MyValue.class)) {
                //获取属性名
                String fieldName = field.getName();
                //获取注解中的值
                String value = field.getAnnotation(MyValue.class).value();
                //获取属性所定义的类型
                String type = field.getType().getName();
                //将属性名改为以大写字母开头,如id改为Id,name改为Name
                fieldName = String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
                //set方法名称,如:setId,setName。。。
                String setterName = "set" + fieldName;
                try {
                    /**
                     * getDeclaredMethod
                     * 获取本类中的所有方法 (只拿本类中的)
                     * getDeclaredMethod(setterName,field.getType())
                     * 第一个参数是方法名,第二个参数是方法参数,传入两个参数后
                     * 就可以根据方法名和方法参数通过反射获取带有参数的方法
                     *
                     * 根据方法名称和参数类型,获取对应的set方法对象
                     */
                    Method method = cls.getDeclaredMethod(setterName, field.getType());
                    try {
                        //判断属性类型,如类型不一致,则转换类型后调用set方法为属性赋值
                        if ("java.lang.Integer".equals(type) || "int".equals(type)) {
                            //转换属性
                            int intValue = Integer.valueOf(value);
                            //利用incoke方法可以根据传入的实例,通过配置的实参来调用方法
                            method.invoke(obj, intValue);
                        }else if ("java.lang.String".equals(type)){
                            method.invoke(obj,value);
                        }
                        //作为测试,仅判断Integer和String类型,其它类型同理
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
    }

最后释放资源

  /**
     * 销毁方法,用于释放资源
     */
    public void close(){
        beanDefinationFactory.clear();
        beanDefinationFactory=null;
        singletonbeanFactory.clear();
        singletonbeanFactory=null;
    }

自此,基于注解实现ioc完成,开始测试~

package spring.ioc;

import com.spring.ioc.ioc_annotation.pojo.PrototypeUser;
import com.spring.ioc.ioc_annotation.pojo.SingletonUser;
import com.spring.ioc.ioc_annotation.applicationContext.AnnotationConfigApplicationContext;

public class IOCAnnotationTest {
    public static void main(String[] args) {
        //创建AnnotationConfigApplicationContext容器
        AnnotationConfigApplicationContext ctx=
                new AnnotationConfigApplicationContext("com.spring.ioc.ioc_annotation.pojo");
        //仅使用key作为参数获取对象,需要强转
        SingletonUser singletonUser1 =(SingletonUser)ctx.getBean("singletonUser");

        System.out.println("单例User对象:"+singletonUser1);

        //使用key和类对象作为参数获取对象,无需强转
        SingletonUser singletonUser2 = ctx.getBean("singletonUser",SingletonUser.class);
        System.out.println("单例User对象"+singletonUser2);

        //仅使用key作为参数获取对象,需要强转
        PrototypeUser prototypeUser1 = (PrototypeUser)ctx.getBean("prototypeUser");
        System.out.println("多例User对象"+prototypeUser1);

        //使用key和类对象作为参数获取对象,无需强转
        PrototypeUser prototypeUser2 = ctx.getBean("prototypeUser",PrototypeUser.class);
        System.out.println("多例User对象"+prototypeUser2);

        ctx.close();

    }

}

测试结果

在这里插入图片描述
总结一下大致流程:
先创建工厂,创建过程中会通过传入的路径初始化,
先将包路径转换为目录路径,然后加载这个目录路径,获取对应的文件夹,然后过滤这个文件夹,将里面的.class文件提取出来保存在一个集合中,在遍历这个集合内的文件,先获取文件的文件名,将文件名第一个字母改为小写作为key,在通过包路径+文件名利用字符串拼接的方式获取到类路径,在利用反射机制找到类路径对应的类生成反射对象,再将key和对象储存在类定义map容器中,至此初始化完成。

初始化完成后,就可以通过getBean方法传入id获取map容器内对应的对象了。
在获取对象中,会先通过id找到这个对象,在判断这个对象上是否有定义的注解,获取到这个注解的值scope。
通过scope的值判断是单例对象还是多例对象,如果是单例对象,则先判断单例容器singletonBeanFactory内有没有改对象的实例,如果没有则通过反射创建一个对象并保存在单例容器中,最后通过id将单例容器内的对象提取出来并返回出去。

如果是多例对象则直接通过反射创建对象并返回出去

在创建对象的过程中,会给对象的成员属性和方法赋值。
他会扫描该对象内所有的成员属性,判断属性上是否标明注解,如果标明了注解,则获取注解的值,接着获取成员属性的名字和类型,将类型和名字进行处理,类型需要转换成统一的类型如 int 和Integer 都转换为Integer,再将名字的首位字母改为大写加上set用字符串拼接成set+Name,找到该类的所有setter方法,并将类型和方法名赋给该类的setter方法,再用反射机制的invoke方法将赋值后的setter方法保存在该对象中,至此,对象赋值完毕。

返回出去的对象就是getBean(beanId)方法的beanId参数获取到的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值