IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Spring源码学习<二> 《手写模拟spring加载Bean的过程》 -> 正文阅读

[Java知识库]Spring源码学习<二> 《手写模拟spring加载Bean的过程》

包结构图:spring包下代表的是模拟spring的源码

?定义@CompontentScan,@Compontent,@Autowired,@Scope

package com.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 ComponentScan {
    String value() default "";
}
=================================================================
package com.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 "";
}
===================================================================
package com.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 {
    String value() default "";
}
=======================================================================
package com.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 "";
}

模拟Spring容器(包含加载bean,创建bean,获取bean)
?

package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//模拟spring容器
public class ShenApplicationContext {
    private Class configClass;
    Map<String,BeanDefinition> beanDefinitionMap=new HashMap<>();
    //创建单例池
    Map<String,Object> singletonObjects=new HashMap<>();
    List<BeanPostProcessor> beanPostProcessorList=new ArrayList<>();

    public ShenApplicationContext(Class configClass) {
        this.configClass = configClass;
        //扫描
        scan(configClass);
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                //如果是单例则存入单例池
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName,BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getType();
        Object instance=null;
        try {
            //通过构造方法实例化  ps:这里只实现了无参的方式
            instance = clazz.getConstructor().newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }
            //获取bean的名字
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware)instance).setBeanName(beanName);
            }
            //初始化前过程
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance= beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }
            //初始化过程
            if(instance instanceof InitializingBean){
                ((InitializingBean)instance).afterPropertiesSet();
            }
            //初始化后过程(模拟AOP过程)
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance= beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return instance;
    }

    public Object getBean(String beanName){
        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new NullPointerException();
        }
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition.getScope().equals("singleton")) {
            //单例   从单例池中取出
            Object singletonBean = singletonObjects.get(beanName);
            //若在单例池中拿不到bean则去创建
            if(null==singletonBean){
                singletonBean= createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        }else {
            //多例  直接创建Bean
            Object prototypeBean = createBean(beanName, beanDefinition);
            return prototypeBean;
        }
    }

    private void scan(Class configClass) {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            //获取包路径
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();
//        System.out.println(path);
            path=path.replace(".", "/");
            //获取类加载器 通过类加载器获取到 .class文件目录
            ClassLoader classLoader = ShenApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file=new File(resource.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    //获取Bean的class文件路径
                    String absolutePath = f.getAbsolutePath();
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    absolutePath = absolutePath.replace("\\", ".");

                    try {
                        Class<?> clazz = classLoader.loadClass(absolutePath);

                        if (clazz.isAnnotationPresent(Component.class)) {
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }
                            String beanName = clazz.getAnnotation(Component.class).value();
                            if("".equals(beanName)){
                                //spring底层生成默认BeanName的方法
                                beanName= Introspector.decapitalize(clazz.getSimpleName());
                            }
                            //如果有Component注解代表这是一个Bean
                            BeanDefinition beanDefinition=new BeanDefinition();
                            beanDefinition.setType(clazz);
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                String value = scopeAnnotation.value();
                                //可能是单例也可能是多例(原型)
                                beanDefinition.setScope(value);
                            }else {
                                //单例
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
    }

}
=====================================================================================
package com.spring;
//Bean的定义 (定义这个bean是否是懒加载,类型是单例还是多例。。。)
public class BeanDefinition {
    private Class type;
    private String scope;
    private boolean isLazy;

    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;
    }

    public boolean isLazy() {
        return isLazy;
    }

    public void setLazy(boolean lazy) {
        isLazy = lazy;
    }
}
====================================================================================
package com.spring;
//spring底层实现初始化的接口
public interface InitializingBean {
    void afterPropertiesSet();
}
===================================================================================
package com.spring;
//spring底层实现初始化前和初始化后接口
public interface BeanPostProcessor {
    default Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }
    default Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}
===================================================================================
package com.spring;
//可以通过这个接口获得bean的名字
public interface BeanNameAware {
    void setBeanName(String name);
}

业务代码:
?

package com.tian;

import com.spring.ShenApplicationContext;
import com.tian.service.UserServiceInterface;

/**
 * 模拟spring创建Bean的过程
 */
public class Test {
    public static void main(String[] args) {
        ShenApplicationContext shenApplicationContext=new ShenApplicationContext(AppConfig.class);
        UserServiceInterface userService = (UserServiceInterface) shenApplicationContext.getBean("userService");
        userService.test();
    }
}
=======================================================================================
package com.tian;

import com.spring.ComponentScan;

@ComponentScan("com.tian.service")
public class AppConfig {

}
=======================================================================================
package com.tian.service;

import com.spring.Autowired;
import com.spring.BeanNameAware;
import com.spring.Component;
import com.spring.Scope;

@Component("userService")
@Scope("singleton")
public class UserService implements UserServiceInterface , BeanNameAware {
    @Autowired
    private OrderService orderService;
    @ShenValue("xxxxx")
    private String test;
    @Override
    public void test(){
        System.out.println(test);
        System.out.println("test");
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("bean的名字"+name);
    }
}
=========================================================================================
package com.tian.service;
public interface UserServiceInterface {
    void test();
}
=======================================================================================
package com.tian.service;

import com.spring.Component;

@Component
public class OrderService {
}
========================================================================================
package com.tian.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.Field;
//初始化前操作
@Component
public class ShenBeanValuePostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        for (Field field : bean.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(ShenValue.class)) {
                field.setAccessible(true);
                try {
                    field.set(bean,field.getAnnotation(ShenValue.class).value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
========================================================================================
package com.tian.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//初始化后操作
@Component
public class ShenBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if(beanName.equals("userService")){
            Object proxyInstance = Proxy.newProxyInstance(ShenBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    return method.invoke(bean, args);

                }
            });
            return proxyInstance;
        }
        return bean;
    }
}
===================================================================================
package com.tian.service;

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 ShenValue {
    String value() default "";
}

运行结果:

?

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-09-07 10:40:45  更:2021-09-07 10:42:50 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:30:10-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码