• 启动Java应用的黑魔法:初始化性能解密@PostConstrut,InitialzingBean,init-method,BeanPostProcessor


    我们在项目中经常会遇到启动时做一些逻辑的处理,比如配置信息的预加载,缓存信息的预加载等等,那都有哪些方法了,我们一起来探讨一下:

    1. 方式

    1. 构造方法初始化: 使用构造方法进行对象的基本属性初始化。这是最基本的初始化方式。

    public class MyBean {
        private String name;
        private int age;
    
        public MyBean(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.JDK @PostConstruct注解: 使用@PostConstruct注解标记一个方法,该方法会在Bean创建后自动调用。

    import javax.annotation.PostConstruct;
    
    public class MyBean {
        private String name;
    
        @PostConstruct
        public void init() {
            // 初始化操作
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3. Spring 的InitializingBean接口: 实现InitializingBean接口,重写afterPropertiesSet()方法,该方法会在Bean创建后自动调用。

    import org.springframework.beans.factory.InitializingBean;
    
    public class MyBean implements InitializingBean {
        @Override
        public void afterPropertiesSet() {
            // 初始化操作
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4.Spring 的@Bean初始化方法: 如果你使用Java配置类定义Bean,可以在@Bean注解中指定初始化方法

    @Configuration
    public class MyConfig {
        
        @Bean(initMethod = "customInitMethod")
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
    class MyBean{
    	private void init(){
    		//初始化操作
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    5.Spring 提供的BeanPostProcessor

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class CustomBeanPostProcessor implements BeanPostProcessor {
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            // 在Bean的初始化前执行自定义操作
            if (bean instanceof MyBean) {
                ((MyBean) bean).setCustomProperty("Custom initialization");
            }
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            // 在Bean的初始化后执行自定义操作
            return bean;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    执行顺序

    首先,创建一个Spring Boot应用程序。

    1.创建Spring Boot应用程序的主类 MySpringBootApplication.java

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MySpringBootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MySpringBootApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2. 创建一个Bean类 MyBean.java

    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.stereotype.Component;
    import javax.annotation.PostConstruct;
    
    @Component
    public class MyBean implements InitializingBean {
    
        public MyBean() {
            System.out.println("Constructor: Bean is being created.");
        }
    
        @PostConstruct
        public void postConstructInit() {
            System.out.println("@PostConstruct: Custom initialization after construction.");
        }
    
        @Override
        public void afterPropertiesSet() {
            System.out.println("InitializingBean: Custom initialization after property set.");
        }
    
        public void customInitMethod() {
            System.out.println("init-method: Custom initialization method defined in Spring Boot.");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    3.创建一个自定义的BeanPostProcessor类 CustomBeanPostProcessor.java

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.stereotype.Component;
    
    @Component
    public class CustomBeanPostProcessor implements BeanPostProcessor {
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("BeanPostProcessor - BeforeInitialization: " + beanName);
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("BeanPostProcessor - AfterInitialization: " + beanName);
            return bean;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    运行Spring Boot应用程序后,您将看到初始化过程中的打印输出。在控制台上,您将看到它们的执行顺序如下:

    Constructor: Bean is being created.
    @PostConstruct: Custom initialization after construction.
    InitializingBean: Custom initialization after property set.
    BeanPostProcessor - BeforeInitialization: myBean
    init-method: Custom initialization method defined in Spring Boot.
    BeanPostProcessor - AfterInitialization: myBean

    这显示了它们的典型执行顺序,即构造方法 > @PostConstruct > InitializingBean > init-method > BeanPostProcessor(在初始化之前和之后执行)。这些初始化方法可以根据需求组合使用,以自定义Bean的初始化过程。

    3.比较

    以下是一个使用Markdown表格形式来比较@PostConstructInitializingBean、自定义初始化方法(@Bean初始化方法)、以及BeanPostProcessor的特点和执行顺序:

    特点/方法@PostConstructInitializingBean自定义初始化方法(@Bean初始化方法)BeanPostProcessor
    需要导入的包import javax.annotation.PostConstruct;import org.springframework.beans.factory.InitializingBean;无需导入特定包import org.springframework.beans.BeansException;
    执行顺序在Bean的构造后执行在Bean的构造后执行在Bean的构造后执行在Bean的初始化前和后执行
    适用对象所有Spring Bean所有Spring Bean所有Spring Bean针对特定Bean或所有Bean
    执行时机Bean创建后,属性设置之后Bean创建后,属性设置之后Bean创建后,属性设置之后Bean创建后,初始化前和后
    用途自定义初始化操作自定义初始化操作自定义初始化操作自定义初始化和后处理操作
    配置方式使用@PostConstruct注解实现InitializingBean接口在Spring配置中使用init-method属性注册为Bean并由Spring容器自动应用
    主要优点简便易用,无需额外接口实现简便易用,无需额外接口实现可用于不使用注解的情况,较灵活强大的自定义初始化和后处理功能
    主要适用场景通常用于自定义初始化逻辑通常用于自定义初始化逻辑在XML配置中使用时比较有用需要高度自定义的初始化和后处理操作
  • 相关阅读:
    【Proteus仿真】【STM32单片机】便携式血糖仪
    PyQt5的笔记(中-4)
    nginx清除缓存
    软件测试之功能测试详解
    【暑期每日一题】洛谷 P7798 [COCI2015-2016#6] PUTOVANJE
    ASM之ClassWriter
    美创科技列为IDC中国数据安全市场代表厂商
    电脑重装系统后usbcleaner怎么格式化u盘
    mysql中的between边界问题
    南昌大学漏洞报送证书
  • 原文地址:https://blog.csdn.net/Hi_alan/article/details/133818409