spring之HelloWord版

目录

基础结构说明

涉及到的功能

执行流程

spring包

引导类

bean定义

注解

回调接口拓展

测试入口

service包

回调接口拓展实现

实体类

自定义注解


基础结构说明

  1. spring子包内,放置spring源码相关类,如注解定义,引导类执行逻辑等

  2. service子包,放置测试类,用于测试spring相关功能,如实体类、自主实现的后处理拓展等

涉及到的功能

  1. componentscan扫描包

  2. component bean注入

  3. Scope bean作用域

  4. beanDefintion bean定义对象

  5. beanDefintionMap bean定义对象集合

  6. getBean 获取容器bean

  7. createBean 创建容器bean

  8. autowird 依赖注入

  9. BeanNameAware 初始化阶段回调拓展

  10. initializingBean 初始化后回调拓展

  11. beanPostProcess bean后置处理器拓展

    1. AOP

    2. vaulue注入

执行流程

引导类构造器(启动入口)

  1. scan扫描(装配BDMap)

    1. 获取引导配置类的扫描注解的路径

    2. 解析处理路径获取类路径下的所有类资源

    3. 遍历所有类

      1. 处理类的相对路径,通过类加载器获取类的class对象

      2. 处理component注解获取beanname

        1. 扫描当前类如果实现了bean后置处理器则加入list

      3. 处理scope注解默认单例

      4. 组装beandeftion对象,组装beanDefinitionMap

  2. 遍历bdMap创建单例对象 多例直接获取的时候创建

    1. createBean创建bean,使用反射获取无参构造器获取对象

    2. aware拓展BeanNameAware拓展 bean初始化的阶段生效

    3. BeanPostProcessor拓展,before处理

    4. InitializingBean初始化后拓展

    5. BeanPostProcessor拓展,after处理

  3. 创建好的bean加入单例池

spring包

引导类

package com.spring;

import com.butch.AppConfig;

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;

//相当于引导类
public class ButchSpringApplicationContext {

    private Class configClass;

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap();

    //单例池
    private Map<String, Object> singletonObjects = new HashMap();

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();



    //构造器进入spring的启动流程
    public ButchSpringApplicationContext(Class configClass){
        this.configClass = configClass;

        //开启扫描包
        scan(configClass);
        
        //遍历bdMap 创建单例对象 多例直接获取的时候创建
        for (Map.Entry<String,BeanDefinition> map : beanDefinitionMap.entrySet()) {
            String beanName = map.getKey();
            BeanDefinition beanDefinition = map.getValue();
            if ("singleton".equals(beanDefinition.getScope())){
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName,bean);
            }

        }

    }

    //创建Bean
    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        //使用反射
        Class type = beanDefinition.getType();
        Object instance = null;
        try {
            instance = type.getConstructor().newInstance();
            //处理依赖注入

            Field[] declaredFields = type.getDeclaredFields();
            //遍历该类所有属性 是否加了依赖注入注解
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(Autowired.class)){
                    //进行依赖注入
                    declaredField.setAccessible(true);
                    declaredField.set(instance,getBean(declaredField.getName()));
                }
            }

            //BeanNameAware拓展 bean初始化的阶段生效
            if (instance instanceof BeanNameAware){
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //后置处理器前扩展
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessBeforeInitialization(instance,beanName);
            }

            if (instance instanceof InitializingBean){
                ((InitializingBean) instance).afterPropertiesSet();
            }


            //后置处理器后扩展
            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;
    }

        //getbean方法
    public Object getBean(String beanName){
        //主要根据BDMap判断获取
        if (!beanDefinitionMap.containsKey(beanName)){
            throw new NullPointerException();
        }
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        //区分单例多例
        if ("singleton".equals(beanDefinition.getScope())){
            //单例直接从单例池获取
            Object singletonBean = singletonObjects.get(beanName);
            if (singletonBean == null){
                singletonBean = createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,singletonBean);
            }
            return singletonBean;
        }else {
            //多例直接创建
            return createBean(beanName, beanDefinition);
        }

    }

    private void scan(Class configClass){
        //获取配置类的注解
        if (configClass.isAnnotationPresent(ComponentScan.class)){
            ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            //处理注解的value路径
            String path = componentScan.value();
            path = path.replaceAll("\\.","/");
            System.out.println("path = " + path);

            //获取应用类加载器
            ClassLoader classLoader = ButchSpringApplicationContext.class.getClassLoader();
            //获取路径下的资源
            URL resource = classLoader.getResource(path);
            //处理资源文件
            File file = new File(resource.getFile());
            if (file.isDirectory()){
                for (File o : file.listFiles()) {
                    String absolutePath = o.getAbsolutePath();
                    //处理类路径 absolutePath = com.butch.serivce.UserService
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    absolutePath = absolutePath.replace("\\", ".");
                    System.out.println("absolutePath = " + absolutePath);
                    //开始装配有component注解的对象
                    try {
                        //通过应用类加载器获取类的class对象
                        Class<?> aClass = classLoader.loadClass(absolutePath);
                        if (aClass.isAnnotationPresent(Component.class)) {
                            //加入自主实现的后置处理器
                            if (BeanPostProcessor.class.isAssignableFrom(aClass)){
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aClass.getConstructor().newInstance();
                                beanPostProcessorList.add(beanPostProcessor);
                            }
                            Component annotation = aClass.getAnnotation(Component.class);
                            //获取beanname
                            String beanName = annotation.value();
                            if ("".equals(beanName)) {
                                //jdk提供的默认beanName
                                beanName = Introspector.decapitalize(aClass.getSimpleName());
                            }
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(aClass);
                            //处理bean是否单例
                            if (aClass.isAnnotationPresent(Scope.class)) {
                                Scope scope = aClass.getAnnotation(Scope.class);
                                String value = scope.value();
                                beanDefinition.setScope(value);
                            } else {
                                //默认单例
                                beanDefinition.setScope("singleton");
                            }
                            //放入bean定义map
                            beanDefinitionMap.put(beanName, beanDefinition);

                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }
    }
    
}

bean定义

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;

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 {


}
package com.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 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;


@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
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;

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

    String value() default "";

}

回调接口拓展

package com.spring;

public interface BeanNameAware {

    void setBeanName(String name);
}
package com.spring;

//bean后置处理器
public interface BeanPostProcessor {

    default Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    default Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}
package com.spring;

//初始化后
public interface InitializingBean {
    void afterPropertiesSet();
}

测试入口

package com.butch;

import com.butch.serivce.UserInterface;
import com.spring.ButchSpringApplicationContext;

public class TestSpring {


    public static void main(String[] args) {

        //开启扫描配置类 -> 创建单例bean
        ButchSpringApplicationContext butchSpringApplication = new ButchSpringApplicationContext(AppConfig.class);

        UserInterface userService = (UserInterface) butchSpringApplication.getBean("userService");
        userService.test();

    }
}

 

package com.butch;

import com.spring.ComponentScan;

@ComponentScan("com.butch.serivce")
public class AppConfig {


}

service包

回调接口拓展实现

package com.butch.serivce;

public interface UserInterface {

    public void test();
}
package com.butch.serivce;

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

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//使用jdk代理实现一个aop
@Component
public class ButchBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if ("userService".equals(beanName)){
            Object proxyInstance = Proxy.newProxyInstance(ButchBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("==========beanPostProcessAop================");
                    Object invoke = method.invoke(bean, args);
                    return invoke;
                }
            });
            return proxyInstance;
        }
        return bean;
    }
}
package com.butch.serivce;

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

import java.lang.reflect.Field;

//注入后置处理
@Component
public class ButchValueBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        for (Field field : bean.getClass().getDeclaredFields()) {
            //查看bean属性是否有value注解
            if (field.isAnnotationPresent(ButchValue.class)){
                //注入值
                field.setAccessible(true);
                try {
                    field.set(bean,field.getAnnotation(ButchValue.class).value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }

        return bean;
    }
}

 

实体类

package com.butch.serivce;

import com.spring.*;

/**
 */
@Component
@Scope
public class UserService implements BeanNameAware,UserInterface,InitializingBean{


    @Override
    public void afterPropertiesSet() {
        System.out.println("==========InitializingBean==========初始化后处理");
    }

    @Autowired
    private OrderService orderService;

    @ButchValue("butch")
    private String name;

    public void test() {
        System.out.println("===============orderService============" + orderService + "=============" + name);
    }

    public void setBeanName(String name) {
        System.out.println("============BeanNameAwar==========" + name);
    }
}
package com.butch.serivce;


import com.spring.Component;

/**
 */

@Component
public class OrderService {

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

自定义注解

package com.butch.serivce;

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

    String value() default "";
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值