spring源码概览

1.反射:动态拿到类的元数据

2.核心源码原理:

package com.example.demo1.spring;

import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.stream.Stream;

public class UserController {

    public static void main(String[] args) throws Exception {

        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        Field userServiceField = clazz.getDeclaredField("userService");
        String name = userServiceField.getName();
        String setMethond = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
        UserService userService = new UserService();
//        userServiceField.setAccessible(true);
//        userServiceField.set(userController, userService);
        Method method = clazz.getMethod(setMethond, UserService.class);
        method.invoke(userController, userService);


        //注解扫描
        Stream.of(clazz.getDeclaredFields()).forEach(field -> {
            String fieldName = field.getName();
            Autowired annotation = field.getAnnotation(Autowired.class);
            if (annotation != null) {
                field.setAccessible(true);
                Class<?> type = field.getType();
                try {
                    Object o = type.getConstructor().newInstance();
                    field.set(userController, o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    static class UserService {

    }
}

3.创建对象(实例化)之前或者之后会有对对象的增强,proccessor(扩展性)

4.设计模式:

为实现扩展性的编码模式,在创建对象之前做一些操作,在容器初始化之前可以做一些操作,在不同的阶段发出不同的事件,做一些操作,抽象出各个接口,面向接口编程,抽象出接口或者定义接口。

5.解耦:

模块化,全部拆成模块,想用啥自己引用就行,

6.上下文:划定一个范围,里面的相关环境数据就是上下文

猜你喜欢

转载自blog.csdn.net/ZhaoXia_hit/article/details/106322496
今日推荐