Spring容器启动过程中的自定义操作插口汇总

下面是总结的几种Spring容器启动时,做自定义初始化操做的方法;也是比较常用,一般做缓存预热,生成消费者启动,数据加载等操作,先于程序运行之前进行数据准备。


@PostConstruct注解

将要执行的方法所在的类上添加@Component注解(交由Spring管理),并且在要执行的方法上添加@PostConstruct注解执行,它用于指定一个方法在Bean被初始化后自动调用,用于执行一些特定的初始化逻辑,如建立数据库连接、加载配置文件、启动线程等。

@Slf4j
@Component
public class PostConstructTest {
    @PostConstruct
    public void postConstruct() {
        log.info("启动时自动执行  @PostConstruct 注解方法");
    }
}

@EventListener方式

将要执行的方法所在的类交给Spring容器扫描(类上添加@Component),并且在要执行的方法上添加@EventListener注解,
用于监听Spring事件并执行相应的操作。使用@EventListener注解的方法可以用来处理Spring中的各种事件

使用@EventListener注解的方法有以下要求:

  • 方法必须是非静态的
  • 方法的参数可以是Spring框架中的事件对象或自定义的对象,方法只会接收与其参数类型匹配的事件。
  • 方法返回类型可以是任意类型,但通常是void类型。
@Slf4j
@Component
public class EventListenerTest {
    @EventListener
    public void handleContextRefreshed(ContextRefreshedEvent event) {
        System.out.println("ContextRefreshedEvent received.");
    }
}

InitializingBean的afterPropertiesSet方法

实现InitializingBean接口,再重写afterPropertiesSet方法,该方法是在bean 初始化的时候执行
在这里插入图片描述
通过实现InitializingBean 接口,然后重写afterPropertiesSet()方法,当Bean的属性设置完成后,Spring容器会自动调用该方法。

使用示例如下

public class MyBean implements InitializingBean {

    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        // 在属性设置完成后执行的初始化逻辑,这里面可以做一些数据初始化,本地缓存预热等操做
        System.out.println("Bean '" + name + "' is being initialized...");
    }
}

afterPropertiesSet()方法是InitializingBean接口中定义的一个方法,用于在Bean属性设置完成后执行一些初始化逻辑,可以通过实现该接口来实现自定义的初始化行为。


实现ApplicationRunner接口重写run方法

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    /**
     * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个ApplicationRunner bean
     * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("启动时自动执行 ApplicationRunner 的 run 方法");

        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            log.info("这是传过来的参数[{}]", optionName);
        }
        String[] sourceArgs = args.getSourceArgs();
        for (String sourceArg : sourceArgs) {
            log.info("这是传过来sourceArgs[{}]", sourceArg);
        }
    }
}

实现AplicationContextAware接口重写setApplicationContext

当一个Bean实现了该接口并重写了setApplicationContext方法,Spring容器会在Bean创建后自动调用这个方法,将容器的上下文对象ApplicationContext传递给该方法。

@Component
public class MyBean implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        // 在这里可以添加一些初始化的操作
    }
}

实现ServletContextListener接口contextInitialized方法

该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行

@Component
public class ServletContextListenerImpl implements ServletContextListener {
    /**
     * 在初始化Web应用程序中的任何过滤器或Servlet之前,将通知所有ServletContextListener上下文初始化。
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("启动时自动执行 ServletContextListener 的 contextInitialized 方法");
    }
}

实现ServletContextAware接口setServletContext 方法

它会在填充普通bean属性之后但在初始化之前调用

@Component
public class ServletContextAwareImpl implements ServletContextAware {
    /**
     * 在填充普通bean属性之后但在初始化之前调用
     * 类似于InitializingBean's 的 afterPropertiesSet 或自定义init方法的回调
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        log.info("启动时自动执行 ServletContextAware 的 setServletContext 方法");
    }
}

继承ContextLoaderListener重写contextInitialized方法

ContextLoaderListener 是一个 Servlet 环境监听器,主要用于在 Web 应用启动时加载 Spring 配置文件,并创建 Spring 容器对象
如果重写了contextInitialized方法,在 Web 应用启动时,该类的 contextInitialized() 方法会被自动调用,从而执行一些自定义的初始化操作。

public class TestContextLoaderListener extends ContextLoaderListener {
    @Override
   	public void contextInitialized(ServletContextEvent event) {
        LoggerUtils.info(logger, "自定义设置开始");

        try {
        	//加载自定义bean
            testBean = ContextLoader.getCurrentWebApplicationContext().getBean("TestBean", TestBean.class);
            //或者可以在此初始化本地缓存之类的
        } catch (Exception e) {
            shutdownApplication(e);
            // Stop application
            throw new RuntimeException(e);
        }
    }
}

如有遗漏,欢迎补充,最后感谢您的阅览!

  • 21
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随身携带的笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值