SpringBoot启动时加载

22 篇文章 0 订阅
6 篇文章 0 订阅

@PostConstruct

启动前加载

  • Spring通过类(标注需要容器管理的类)的构造方法创建好一个Bean
  • 执行自动注入,@Autowired @Resource
  • 执行@PostConstruct标注的方法

该注解被用来修饰一个非静态的void方法,被@PostConstruct修饰的方法会在加载Servlet的时候运行,并且只会被执行一次。

  • 该注解是JDK自带的。

测试代码如下:

import javax.annotation.PostConstruct;

@Slf4j
@Service
public class ArticleServiceImpl {

    @PostConstruct
    public void init() {
        log.info("@PostConstruct标注...");
    }

}

ApplicationListener

服务器容器初始化完毕之后、SpringBoot启动完毕之前加载。

  • 也就是当所有的Bean都已经处理完毕之后。
  • Spring容器就会发布一个ContextRefreshedEvent事件,从而触发所有实现ApplicationListener的类方法得以执行。

应用监听器,我们实现ApplicationListener接口,将其放在Spring容器中,在服务器容器初始化完毕之后SpringBoot启动完毕之前,就会执行实现的方法。

主要代码如下:

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
        //这里可能会存在两个容器 分别是应用容器(根容器)和Web容器 那么加载时就可能会加载两次
        if (event.getApplicationContext().getParent() == null) {
            //Web容器的父容器是应用容器 这里我们获取其父类来判定是不是最顶层的应用容器
            log.info("ApplicationListener初始化...");
        }
    }
}

CommandLineRunner和ApplicationRunner

在SpringBoot启动成功之后才会执行。

  • SpringBoot项目启动成功之后,就会执行所有CommandLineRunner和ApplicationRunner实现类的实现方法。
  • 执行顺序可自行设置。未设置就按照加载先后顺序进行执行。

都是实现其对应的接口即可。

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunner初始化...");
    }
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("CommandLineRunner初始化...");
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值