【吃透Java手写】1- Spring(上)-启动-扫描-依赖注入-初始化-后置处理器

news2024/10/5 21:43:26

【吃透Java手写】Spring(上)启动-扫描-依赖注入-初始化-后置处理器

  • 1 准备工作
    • 1.1 创建自己的Spring容器类
    • 1.2 创建自己的配置类 @ComponentScan
    • 1.3 @ComponentScan
      • 1.3.1 @Retention
      • 1.3.2 @Target
    • 1.4 用户类UserService @Component
    • 1.5 @Component
    • 1.6 测试类
  • 2 启动和扫描逻辑模拟实现
    • 2.1 解析配置类-获取扫描路径
    • 2.2 解析配置类-扫描
      • 2.2.1 通过包名来获取类
      • 2.2.2 判断是否为Bean对象
      • 2.2.3 单例/原型Bean实现
        • 2.2.3.1 单例池
        • 2.2.3.2 BeanDefinition池
        • 2.2.3.3 单例Bean实例化
        • 2.2.3.4 原型Bean实例化
        • 2.2.3.5 测试
  • 3 依赖注入模拟实现
    • 3.1 @Autowired
    • 3.2 为UserService引入OrderService依赖
    • 3.3 BeanNameAware接口
  • 4 初始化机制模拟实现
    • 4.1 InitializingBean接口
  • 5 BeanPostProcessor模拟实现
    • 5.1 BeanPostProcessor接口
    • 5.2 具体实现类
    • 5.3 Spring扫描时对BeanPostProcessor实现类处理
    • 5.4 BeanPostProcessor实现类初始换前后处理
    • 5.5 测试


1 准备工作

在这里插入图片描述

1.1 创建自己的Spring容器类

创建com.spring.ZhouyuApplicationContext

public class ZhouyuApplicationContext {
    private Class configClass;

    public ZhouyuApplicationContext(Class configClass) {
        this.configClass = configClass;
        //解析配置类
        //ComponentScan注解--->扫描路径--->扫描

    }

    public Object getBean(String beanName) {
        return null;
    }
}
  • public ZhouyuApplicationContext(Class configClass)用配置类来初始换容器
  • public Object getBean(String beanName)获取bean方法
  • 获取到配置类会通过解析配置类来完成对容器的初始化->//解析配置类,这里的解析,Spring只会解析Spring中提供的注解,对于自定义的注解是无法自动解析的

1.2 创建自己的配置类 @ComponentScan

创建com.zhouyu.AppConfig

import com.spring.ComponentScan;

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

配置类需要定义扫描路径,则需要创建@ComponentScan注解

@ComponentScan("com.zhouyu.service")定义扫描路径为"com.zhouyu.service"

1.3 @ComponentScan

@ComponentScan是Spring用于扫描路径的注解,所以在Spring目录下

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentScan {
    String value() default "";
}

1.3.1 @Retention

  • @Retention(RetentionPolicy.RUNTIME)注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;

    1、RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;

    2、RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;

    3、RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;

首先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。

1.3.2 @Target

  • @Target(ElementType.TYPE)可以用于类、接口和枚举类型。

@Target注解用于指定注解可以应用的程序元素类型,它有一个ElementType枚举类型的参数,可以取值为:

ElementType.TYPE:可以用于类、接口和枚举类型。

ElementType.FIELD:可以用于字段(包括枚举常量)。

ElementType.METHOD:可以用于方法。

ElementType.PARAMETER:可以用于方法的参数。

ElementType.CONSTRUCTOR:可以用于构造函数。

ElementType.LOCAL_VARIABLE:可以用于局部变量。

ElementType.ANNOTATION_TYPE:可以用于注解类型。

ElementType.PACKAGE:可以用于包。

ElementType.TYPE_PARAMETER:可以用于类型参数声明(Java 8新增)。

ElementType.TYPE_USE:可以用于使用类型的任何语句中(Java 8新增)。

  • String value() default ""定义扫描路径,默认值为空

1.4 用户类UserService @Component

创建com.zhouyu.service.UserService

@Component("userService")
public class UserService {
}

@Component("userService")定义Bean,value的值表示Bean的名字,如果不写的话Spring会解析你的类名,然后小写首字母当作Bean名

1.5 @Component

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Component {
    String value() default "";
}

规则与@ComponentScan类似

1.6 测试类

创建com.zhouyu.Test

public class Test {
    public static void main(String[] args) {
        ZhouyuApplicationContext context = new ZhouyuApplicationContext(AppConfig.class);
        Object userService = context.getBean("userService");
    }
}

2 启动和扫描逻辑模拟实现

2.1 解析配置类-获取扫描路径

在com.spring.ZhouyuApplicationContext中

public class ZhouyuApplicationContext {
    private Class configClass;

    public ZhouyuApplicationContext(Class configClass) {
        this.configClass = configClass;
        //解析配置类
        ComponentScan componentScanAnnotations = (ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);
        //扫描路径
        String path= componentScanAnnotations.value();
        System.out.println("扫描路径:"+path);
    }

    public Object getBean(String beanName) {
        return null;
    }
}
  • configClass.getDeclaredAnnotation拿到注解,通过.value拿到注解的值

运行得到包名

扫描路径:com.zhouyu.service

2.2 解析配置类-扫描

当com.zhouyu.service下有很多类时,有些类是我们Spring不关心的类,我们Spring关心的是加了@Component注解的类,这样就把这些作为Bean然后放在容器中

2.2.1 通过包名来获取类

这里需要用到类加载器

  • 引导类加载器 Bootstrap,加载属于JVM的一部分,由C++代码实现,负责加载<JAVA_HOME\>\jre\lib路径下的核心类库,由于安全考虑只加载 包名 java、javax、sun开头的类。
  • 扩展类加载器 ExtClassLoader,扩展类加载器的父加载器是Bootstrap启动类加载器 (注:不是继承关系)。扩展类加载器负责加载<JAVA_HOME>\jre\lib\ext目录下的类库。
  • 系统类加载器 AppClassLoader,系统类加载器的父加载器是ExtClassLoader扩展类加载器(注: 不是继承关系)。系统类加载器负责加载 classpath环境变量所指定的类库,是用户自定义类的默认类加载器。
D:\Software\software_with_code\idea\jdk\jdk-17\bin\java.exe "-javaagent:D:\Software\software_with_code\idea\software\IntelliJ IDEA 2023.2\lib\idea_rt.jar=47035:D:\Software\software_with_code\idea\software\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath D:\Code\JavaCode\mySpring\mySpring\target\classes com.zhouyu.Test
扫描路径:com.zhouyu.service

刚刚获取扫描路径时最后指定的classpath,说明运行的是系统类加载器AppClassLoader。classpath的路径是D:\Code\JavaCode\mySpring\mySpring\target\classes,所以获取类加载的相对路径就是这个。

在这里插入图片描述

public ZhouyuApplicationContext(Class configClass) {
    this.configClass = configClass;
    //解析配置类
    ComponentScan componentScanAnnotations = (ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);
    //ComponentScan注解--->扫描路径--->扫描
    //扫描路径
    String path= componentScanAnnotations.value();
    System.out.println("扫描路径:"+path);
    //获取类加载器
    ClassLoader classLoader = ZhouyuApplicationContext.class.getClassLoader();
    URL resource =classLoader.getResource("com/zhouyu/service");
    File file=new File(resource.getFile());
    if(file.isDirectory()){
        File[] files=file.listFiles();
        for(File f:files){
            System.out.println(f);
        }
    }
}

输出

扫描路径:com.zhouyu.service
D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\UserService.class
D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\XxUtil.class

这样获取了类,也就能获取类上的注解了

public ZhouyuApplicationContext(Class configClass) {
    this.configClass = configClass;
    //解析配置类
    ComponentScan componentScanAnnotations = (ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);
    //ComponentScan注解--->扫描路径--->扫描
    //扫描路径
    String path= componentScanAnnotations.value();
    System.out.println("扫描路径:"+path);
    //获取类加载器
    ClassLoader classLoader = ZhouyuApplicationContext.class.getClassLoader();
    URL resource =classLoader.getResource("com/zhouyu/service");
    File file=new File(resource.getFile());
    if(file.isDirectory()){
        File[] files=file.listFiles();
        for(File f:files){
            System.out.println(f);
            Class<?> aClass = classLoader.loadClass("xxx");
            if(aClass.isAnnotationPresent(Component.class)){
                //..
            }
        }
    }
}

但是我们获取到的类是编译好的

D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\UserService.class
D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\XxUtil.class

怎么才能加载原先的com.zhouyu.service.UserService这样的路径呢?这样就要将D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\UserService.class``转换为com.zhouyu.service.UserService,掐头去尾,把\换成.

String fileName=f.getAbsolutePath();
if(fileName.endsWith(".class")){
    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
    className = className.replace("\\", ".");

ZhouyuApplicationContext全部代码

  • 先获取扫描路径(com.zhouyu.service)—>
  • 转换为相对路径(com/zhouyu/service)—>
  • 通过相对路径获取类加载器获取编译好的类—>
  • 获取编译好的类的路径名(D:\Code\JavaCode\mySpring\mySpring\target\classes\com\zhouyu\service\UserService.class)—>
  • 转换为可获取的类名(com.zhouyu.service.UserService)—>
  • 判断是否有注解Component来决定是不是Bean对象
public ZhouyuApplicationContext(Class configClass) {
    this.configClass = configClass;
    //解析配置类
    ComponentScan componentScanAnnotations = (ComponentScan)configClass.getDeclaredAnnotation(ComponentScan.class);
    //ComponentScan注解--->扫描路径--->扫描
    //扫描路径
    String path= componentScanAnnotations.value();
    path = path.replace(".", "/");
    //System.out.println("扫描路径:"+path);
    //获取类加载器
    ClassLoader classLoader = ZhouyuApplicationContext.class.getClassLoader();
    URL resource =classLoader.getResource(path);
    File file=new File(resource.getFile());
    if(file.isDirectory()){
        File[] files=file.listFiles();
        for(File f:files){
            //System.out.println(f.getAbsolutePath());
            String fileName=f.getAbsolutePath();
            if(fileName.endsWith(".class")){
                String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                className = className.replace("\\", ".");
                try {
                    Class<?> aClass = classLoader.loadClass(className);
                    if(aClass.isAnnotationPresent(Component.class)){
                        //有Component注解表示这个类是一个Bean需要被Spring管理
                    }
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

2.2.2 判断是否为Bean对象

在Spring中的Bean对象也分为单例Bean和原型Bean

@Component("userService")
public class UserService {
}

如果没有指定@Scope,则默认为单例Bean

@Scope取值:

  • singleton:此取值时表明容器中创建时只存在一个实例,所有引用此bean都是单一实例。
  • prototype:每次获取一个不同的Bean对象

如果加上@Scope("prototype")则代表是原型Bean

@Component("userService")
@Scope("prototype")
public class UserService {
}

2.2.3 单例/原型Bean实现

2.2.3.1 单例池

底层有一个map对象,map<beanName,bean对象>,如果获取的相同的beanName,则通过单例池来获取相同的Bean对象

在com.spring.ZhouyuApplicationContext中实现单例池

//单例池
private ConcurrentHashMap<String,Object>singletonObjects=new ConcurrentHashMap<String,Object>();
  • HashMap
    HashMap是线程不安全的,因为HashMap中操作都没有加锁,因此在多线程环境下会导致数据覆盖之类的问题,所以,在多线程中使用HashMap是会抛出异常的。

  • HashTable
    HashTable是线程安全的,但是HashTable只是单纯的在put()方法上加上synchronized。保证插入时阻塞其他线程的插入操作。虽然安全,但因为设计简单,所以性能低下。

  • ConcurrentHashMap
    ConcurrentHashMap是线程安全的,ConcurrentHashMap并非锁住整个方法,而是通过原子操作和局部加锁的方法保证了多线程的线程安全,且尽可能减少了性能损耗。

在获取Component注解后,判断是否为单例Bean,如果是,就需要生成Bean对象然后放入单例池中。

2.2.3.2 BeanDefinition池

在Spring中如果要getBean,拿到beanName则需要每次都要解析Bean对象的注解,这样相当麻烦,因此在Spring中,统一为解析Bean时生成BeanDefinition

生成com.spring.BeanDefinition

public class BeanDefinition {
    //名字
    private Class clazz;
    //作用域
    private String scope;
    public Class getClazz() {
        return clazz;
    }
    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }
    public String getScope() {
        return scope;
    }
    public void setScope(String scope) {
        this.scope = scope;
    }
}

扫描Bean时如果有Component注解就要创建BeanDefinition对象,再根据是否有Scope填充相应BeanDefinition对象的属性

if(aClass.isAnnotationPresent(Component.class)){
    //有Component注解表示这个类是一个Bean需要被Spring管理
    ComponentScan componentAnnotations = aClass.getDeclaredAnnotation(ComponentScan.class);
    String beanName = componentAnnotations.value();
    BeanDefinition beanDefinition = new BeanDefinition();
    beanDefinition.setClazz(aClass);
    if(aClass.isAnnotationPresent(Scope.class)){
        //原型Bean
        Scope aClassDeclaredAnnotation = aClass.getDeclaredAnnotation(Scope.class);
        beanDefinition.setScope(aClassDeclaredAnnotation.value());
    }else{
        //单例Bean
        beanDefinition.setScope("singleton");
    }
    beanDefinitionMap.put(beanName,beanDefinition);


}
2.2.3.3 单例Bean实例化

Spring启动时就要完成单例Bean实例化

在完成扫描后,要对单例池中的实例进行实例化,将以前的方法抽成一个方法scan

public ZhouyuApplicationContext(Class configClass) {
        this.configClass = configClass;
        //解析配置类
        scan(configClass);
        //针对单例池中的Bean要在Spring启动的时候进行实例化
        for(Map.Entry<String,BeanDefinition> entry:beanDefinitionMap.entrySet()){
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                //创建Bean
                Object bean = createBean(beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }
2.2.3.4 原型Bean实例化

在获取bean方法时,获取对应的BeanDefinition,如果是单例bean,则从单例池直接返回,如果不是则需要创建bean

public Object getBean(String beanName) {
    if (beanDefinitionMap.containsKey(beanName)) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition.getScope().equals("singleton")) {
            //单例Bean
            Object o = singletonObjects.get(beanName);
            return o;
        } else {
            //原型Bean
            return createBean(beanDefinition);
        }
    } else {
        throw new RuntimeException("Not found [" + beanName + "] BeanDefinition");
    }
}
private Object createBean(BeanDefinition beanDefinition) {
    Class clazz = beanDefinition.getClazz();
    try {
        Object o = clazz.getDeclaredConstructor().newInstance();
        return o;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

通过beanDefinition.getClazz().getDeclaredConstructor().newInstance()获取实例。

2.2.3.5 测试
public class Test {
    public static void main(String[] args) {
        ZhouyuApplicationContext context = new ZhouyuApplicationContext(AppConfig.class);
        Object userService = context.getBean("userService");
        Object userService1 = context.getBean("userService");
        Object userService2 = context.getBean("userService");
        System.out.println(userService);
        System.out.println(userService1);
        System.out.println(userService2);
    }
}

userService是一个原型Bean,可以看出每回获取的Bean对象地址都不同

com.zhouyu.service.UserService@2e5d6d97
com.zhouyu.service.UserService@238e0d81
com.zhouyu.service.UserService@31221be2

如果去掉@Scope("prototype")

@Component("userService")
//@Scope("prototype")
public class UserService {
}

输出

com.zhouyu.service.UserService@7daf6ecc
com.zhouyu.service.UserService@7daf6ecc
com.zhouyu.service.UserService@7daf6ecc

则全是单例bean

3 依赖注入模拟实现

3.1 @Autowired

创建com.spring.Autowired

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Autowired {
}

3.2 为UserService引入OrderService依赖

创建com.zhouyu.service.OrderService

@Component("orderService")
public class OrderService {
}

引入依赖

@Component("userService")
//@Scope("prototype")
public class UserService {
    @Autowired
    private OrderService orderService;

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

这样引入test方法

public class Test {
    public static void main(String[] args) {
        ZhouyuApplicationContext context = new ZhouyuApplicationContext(AppConfig.class);
        UserService userService = (UserService)context.getBean("userService");
        userService.test();
    }
}

在main中调用userService.test()则为空,因为依赖注入后并没有任何操作

null

一般来说我们依赖注入后,Spring就应该为我们赋好值了。

因此我们需要在创建Bean是准备好这一切。在com.spring.ZhouyuApplicationContext#createBean中

Class clazz = beanDefinition.getClazz();
try {
    Object o = clazz.getDeclaredConstructor().newInstance();
    //依赖注入
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Autowired.class)) {
            Object bean = getBean(field.getName());
            if(bean==null) {
                throw new RuntimeException("Not found [" + field.getName() + "] BeanDefinition");
            }
            field.setAccessible(true);
            field.set(o, bean);
        }
    }
    return o;
}
  • field.setAccessible(true):设置了setAccessible为true之后,就能编辑final变量以及访问private变量。

在这里插入图片描述

重新测试userService.test(),得到

com.zhouyu.service.OrderService@433c675d

3.3 BeanNameAware接口

BeanNameAware 主要用于获取在 Spring 容器中配置的 Bean 名称,使得 Bean 能够获取自身在容器中的标识。

创建com.spring.BeanNameAware

public interface BeanNameAware {
    void setBeanName(String name);
}

就可以在UserService中实现这个接口,在创建Bean时就可以添加beanName

@Component("userService")
//@Scope("prototype")
public class UserService implements BeanNameAware {
    @Autowired
    private OrderService orderService;
    private String beanName;
    
    @Override
    public void setBeanName(String name) {
        beanName = name;
    }
    public void test() {
        System.out.println(orderService);
        System.out.println("userService beanName: " + beanName);
    }
}

在com.spring.ZhouyuApplicationContext#createBean中

private Object createBean(String beanName,BeanDefinition beanDefinition) {
    Class clazz = beanDefinition.getClazz();
    try {
        Object o = clazz.getDeclaredConstructor().newInstance();
        //依赖注入
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Autowired.class)) {
                Object bean = getBean(field.getName());
                if(bean==null) {
                    throw new RuntimeException("Not found [" + field.getName() + "] BeanDefinition");
                }
                field.setAccessible(true);
                field.set(o, bean);
            }
        }
        if(o instanceof BeanNameAware){
            ((BeanNameAware) o).setBeanName(beanName);
        }
        return o;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
  • o instanceof BeanNameAware判断是否实现BeanNameAware,如果实现了就把Object类转为其实现的BeanNameAware的接口类,并调用其setBeanName完成赋值。

4 初始化机制模拟实现

4.1 InitializingBean接口

InitializingBean是Spring提供的拓展性接口,InitializingBean接口为bean提供了属性初始化后的处理方法,它只有一个afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。

创建com.spring.InitializingBean

public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}

UserService实现InitializingBean接口

@Component("userService")
//@Scope("prototype")
public class UserService implements InitializingBean {
    @Autowired
    private OrderService orderService;
        @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化方法");
    }
	//InitializingBean模拟实现
    public void test() {
        System.out.println(orderService);
        //System.out.println("userService beanName: " + beanName);
    }
}

在其创建bean时,对是否实现InitializingBean接口进行判断,在com.spring.ZhouyuApplicationContext#createBean中

//初始化方法
if(o instanceof InitializingBean){
    ((InitializingBean) o).afterPropertiesSet();
}
private Object createBean(String beanName,BeanDefinition beanDefinition) {
    Class clazz = beanDefinition.getClazz();
    try {
        Object o = clazz.getDeclaredConstructor().newInstance();
        //依赖注入
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Autowired.class)) {
                Object bean = getBean(field.getName());
                if(bean==null) {
                    throw new RuntimeException("Not found [" + field.getName() + "] BeanDefinition");
                }
                field.setAccessible(true);
                field.set(o, bean);
            }
        }
        //Aware回调
        if(o instanceof BeanNameAware){
            ((BeanNameAware) o).setBeanName(beanName);
        }
        //初始化方法
        if(o instanceof InitializingBean){
            ((InitializingBean) o).afterPropertiesSet();
        }

        return o;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

5 BeanPostProcessor模拟实现

该接口我们也叫后置处理器,作用是在Bean对象在实例化和依赖注入完毕后,在显示调用初始化方法的前后添加我们自己的逻辑。

注意是Bean实例化完毕后及依赖注入完成后触发的。

5.1 BeanPostProcessor接口

创建com.spring.BeanPostProcessor接口

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception;

    Object postProcessAfterInitialization(Object bean, String beanName) throws Exception;
}

5.2 具体实现类

创建com.zhouyu.service.ZhouyuBeanPostProcessor实现BeanPostProcessor接口,并且用@Component交给Spring管理

@Component("zhouyuBeanPostProcessor")
public class ZhouyuBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        System.out.println(beanName+"初始化方法之前");
        if(beanName.equals("userService")) {
            System.out.println("userService初始化方法之前");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        System.out.println(beanName+"初始化方法之后");
        if(beanName.equals("userService")) {
            System.out.println("userService初始化方法之后");
        }
        return bean;
    }
}

5.3 Spring扫描时对BeanPostProcessor实现类处理

因为ZhouyuBeanPostProcessor对实例方法前后都进行处理,所以需要在扫描时对实现BeanPostProcessor的类进行处理

要保证BeanPostProcessor接口的实现类率先被实例化,扫描顺序无所谓。

在com.spring.ZhouyuApplicationContext中用一个List来存放BeanPostProcessor接口的实现类

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

在com.spring.ZhouyuApplicationContext#scan中,对于判断这个类是否实现BeanPostProcessor接口,不能使用instanceof BeanPostProcessor因为该实现类还未被实例化。

所以需要使用BeanPostProcessor.class.isAssignableFrom(aClass)判断是否实现BeanPostProcessor接口

再调用aClass.getDeclaredConstructor().newInstance()进行实例化再放入List中

try {
    Class<?> aClass = classLoader.loadClass(className);
    if(aClass.isAnnotationPresent(Component.class)){
        //判断是否实现了BeanPostProcessor接口
        if(BeanPostProcessor.class.isAssignableFrom(aClass)){
            BeanPostProcessor instance = (BeanPostProcessor) aClass.getDeclaredConstructor().newInstance();
            beanPostProcessorsList.add(instance);
        }

        //有Component注解表示这个类是一个Bean需要被Spring管理
        Component componentAnnotations = aClass.getDeclaredAnnotation(Component.class);
        String beanName = componentAnnotations.value();
        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setClazz(aClass);
        if(aClass.isAnnotationPresent(Scope.class)){
            //原型Bean
            Scope aClassDeclaredAnnotation = aClass.getDeclaredAnnotation(Scope.class);
            beanDefinition.setScope(aClassDeclaredAnnotation.value());
        }else{
            //单例Bean
            beanDefinition.setScope("singleton");
        }
        beanDefinitionMap.put(beanName,beanDefinition);
    }
}

这里在扫描到BeanPostProcessor接口创建了一次实例,在扫描Component注解又单例实例化了一次,有些不严谨。

Spring源码是使用createBean进行创建原型的,这也就可以在实现类中支持一些@Autowired的其他操作。这里只提供一种解决方法。

5.4 BeanPostProcessor实现类初始换前后处理

因为BeanPostProcessor是对初始化前后进行操作的,所以需要在对其他Bean对象创建时的初始化方法时进行处理

在com.spring.ZhouyuApplicationContext#createBean中

//BeanPostProcessor初始化方法之前
for(BeanPostProcessor beanPostProcessor:beanPostProcessorsList){
    o = beanPostProcessor.postProcessBeforeInitialization(o,beanName);
}
//初始化方法
if(o instanceof InitializingBean){
    ((InitializingBean) o).afterPropertiesSet();
}
//BeanPostProcessor初始化方法之后
for(BeanPostProcessor beanPostProcessor:beanPostProcessorsList){
    o = beanPostProcessor.postProcessAfterInitialization(o,beanName);
}

5.5 测试

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1653276.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

吴恩达机器学习笔记:第 9 周-16推荐系统(Recommender Systems) 16.3-16.4

目录 第 9 周 16、 推荐系统(Recommender Systems)16.3 协同过滤16.4 协同过滤算法 第 9 周 16、 推荐系统(Recommender Systems) 16.3 协同过滤 在之前的基于内容的推荐系统中&#xff0c;对于每一部电影&#xff0c;我们都掌握了可用的特征&#xff0c;使用这些特征训练出了…

TikTok 正式起诉美国政府;全新 iPad Pro 将搭载苹果 M4 芯片丨 RTE 开发者日报 Vol.199

开发者朋友们大家好&#xff1a; 这里是 「RTE 开发者日报」&#xff0c;每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享 RTE&#xff08;Real Time Engagement&#xff09; 领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「…

视频号小店想要长久发展,做店的核心是什么?一篇详解!

大家好&#xff0c;我是电商小V 想要做好视频号小店&#xff0c;那么他的核心是什么呢&#xff1f; 视频号小店的核心还是商品&#xff0c;其实电商运营底层的逻辑都是一样的&#xff0c;都是以商品为核心去运营的&#xff0c;再说的浮夸一点就是&#xff0c;你的商品选择的好&…

ICode国际青少年编程竞赛- Python-2级训练场-基础训练4

ICode国际青少年编程竞赛- Python-2级训练场-基础训练4 1、 for i in range(4):if i > 2:Flyer[i].step(3)else:Flyer[i].step(1) Dev.step(Item[3].x - Dev.x)2、 for i in range(6):if i < 3:Flyer[i].step(2)else:Flyer[i].step(3) Dev.step(Item[2].x - Dev.x)3、 …

linux Nginx安装与启动

一、先到官网下载Nginx 官网地址&#xff1a; http://nginx.org/en/download.html 我下载的是nginx-1.20.2 二、下载好的文件上传到服务器&#xff0c;然后解压 1、上传到指定的服务器地址&#xff0c;我这里是公司服务器&#xff0c;目录都是定义好的&#xff0c;自己玩建…

哪个文件加密软件好?迅软加密软件特性解析

哪个文件加密软件好&#xff1f; 这里推荐一款好用的文件加密软件&#xff0c;迅软DSE加密软件&#xff0c;有17年的加密经验了&#xff0c;已为三十万企业解决信息安全问题。简单易用&#xff0c;兼容性强&#xff0c;各类型文件都可加密。完善的售后保障&#xff0c;各地有服…

C++之STL-priority_queue和仿函数的讲解

目录 一、priority_queue的介绍和使用 1.1 priority_queue的介绍 1.2 priority_queue的基本接口 二、仿函数的介绍 2.1 基本概念 2.2 适用场景 三、模拟实现priority_queue 3.1 向上调整算法 3.2 向下调整算法 3.3 整体框架 一、priority_queue的介绍和使用 1.1 prio…

数据可视化训练第一天(matplotlib直线;散点图,随机漫步)

前言 本人自己的练习记录&#xff1b;如有错误请指正&#xff1b; https://matplotlib.org/stable/gallery/lines_bars_and_markers/index.html 官方有许多例子&#xff0c;可以找到自己需要的图像模仿进行绘制 1.一个简单的直线例子 就如同我们学习C语言的第一个helloword时…

白话机器3:PCA与SVM详细数学原理

一、PCA数学原理 1.数据标准化 首先&#xff0c;需要对原始数据进行标准化处理&#xff0c;使得每个特征的均值为0&#xff0c;方差为1。假设有一个的数据矩阵X&#xff0c;其中每一列是一个样本&#xff0c;每一行是一个特征。 标准化公式如下&#xff1a; 其中&#xff0c;…

加速数据要素流通,“隐语杯”全国高校隐私计算大赛正式启动报名!

当前&#xff0c;我国数字经济正处在一个快速增长的阶段&#xff0c;数据要素逐渐成为促进社会经济繁荣的关键驱动力。随着国家对数据治理及隐私保护政策的不断完善&#xff0c;隐私计算技术的创新和实践应用变得愈发重要。面对数据安全与隐私保护的双重挑战&#xff0c;如何实…

系统稳定性判定分析(二)----频域分析法相关辐角原理

文章目录 辐角原理&#xff08;即Cauchy原理&#xff09;引理分析辐角原理定义与证明 参考文献 为后续更好从频域层面分析控制系统的稳定性&#xff0c;本节首先介绍在后续分析中用到的辐角原理。 根据复变函数对数的定义&#xff0c;有 l n f ( s ) l n ∣ f ( z ) ∣ i ( a…

libcity笔记:libcity/evaluator/traj_loc_pred_evaluator.py

1 构造函数 2 _check_config 检查配置是否符合评估器的要求&#xff0c;确保评估过程能够顺利执行 3 collect 4 evaluate 5 save_result & clear

如何使用多协议视频汇聚/视频安防系统EasyCVR搭建智慧园区视频管理平台?

智慧园区作为现代化城市发展的重要组成部分&#xff0c;不仅承载着产业升级的使命&#xff0c;更是智慧城市建设的重要体现。随着产业园区竞争的逐渐白热化&#xff0c;将项目打造成完善的智慧园区是越来越多用户关注的内容。 然而我们往往在规划前期就开始面临众多难题&#…

三、Redis五种常用数据结构-Hash

Hash是redis中常用的一种无序数据结构。结构类似HashMap。 具体结构如下&#xff1a;key field value 1、优缺点 1.1、优点 同类数据归类整合储存&#xff0c;方便数据管理。相比于string操作消耗内存和CPU更小。分字段存储&#xff0c;节省网络流量。 1.2、缺点 过期时间…

基于边缘智能网关的工业燃气管网监测应用

随着城市化和工业化的飞速发展&#xff0c;燃气的使用量和应用范围持续增加&#xff0c;燃气管网作为承载燃气输送的设施&#xff0c;安全问题至关重要。一旦燃气管网发生泄漏事故&#xff0c;极易引发起火、爆炸等&#xff0c;从而酿成人员伤亡及财产损失的恶性事故。 得益于物…

VMware 虚拟机自定义规范 - 更优雅的虚拟机开局

介绍 虚拟机自定义规范可以在你克隆虚拟机的时候在vCenter 的Web界面设定虚拟机的主机名、单/多网卡IP的IP和网关、DNS服务器、唯一标识符重置&#xff08;SID等&#xff09;、硬盘分区自动扩容、设定密码、密钥、时区等信息。 让管理员不需要进入虚拟机系统内部进行配置&…

运用远期交易防范外汇风险

随着全球化的深入&#xff0c;跨境贸易和投资愈加频繁&#xff0c;外汇风险成为各类企业和投资者必须面对的现实问题。汇率的波动可能导致交易和投资的成本大幅增加&#xff0c;甚至引发利润损失。在这种情况下&#xff0c;远期交易作为一种有效的外汇风险对冲工具&#xff0c;…

Springboot整合飞书向群组/指定个人发送消息/飞书登录

Springboot整合飞书向群组发送消息 飞书开放平台创建企业自建应用 添加应用能力-机器人 创建完成后&#xff0c;进入应用详情页&#xff0c;可以在首页看到 App Id 和 App Secret 在飞书pc端创建一群机器人 此处可以拿到该机器人的webhook地址,通过https的方式,也可以调用发送…

人大金仓报The connection attempt failed.Reason:Connection reset解决办法

在连接人大京仓数据库 的时候报下面的错误 解决办法&#xff1a; 更换这里的IP地址就行&#xff0c;不要用127.0.0.1&#xff0c;然后就可以了

Android单行字符串末尾省略号加icon,图标可点击

如图 设置仅显示单行字符串&#xff0c;末尾用省略号&#xff0c;加跟一个icon&#xff0c;icon可点击 tvName.text "test"val drawable ResourcesCompat.getDrawable(resources, R.mipmap.icon_edit, null)tvName.setCompoundDrawablesWithIntrinsicBounds(null,…