SpringBoot启动时自动执行代码的几种方式

在开放SpringBoot项目时, 需要在启动后加载一些资源,或者是把一些热数据放到缓存中

如果不需要使用到springIOC中的bean时, 可以用 static ,或者是构造方法加载这些资源

如果需要使用IOC中的bean时

1. @PostConstruct

PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。

2. CommandLineRunner 和 ApplicationRunner

SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunnerApplicationRunner

这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

ApplicationArguments
官方文档解释为:

Provides access to the arguments that were used to run a SpringApplication.

在Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(…)的应用参数。

3. … Aware 类

这些Aware类基本都是做一些特定事件的, 当然不管它原来是干嘛的, 它只要是在启动后执行, 就可以做一些自己想做的事情呗

执行顺序

@Component
public class Test implements ApplicationRunner, CommandLineRunner, ApplicationContextAware, BeanNameAware
{
    @PostConstruct
    public void run ()
    {
        System.err.println("PostConstruct");
    }

    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        System.err.println("ApplicationRunner");
    }

    @Override
    public void run(String... args) throws Exception
    {
        System.err.println("CommandLineRunner");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        System.err.println("ApplicationContextAware");
    }

    @Override
    public void setBeanName(String s)
    {
        System.err.println("BeanNameAware");
    }
}

BeanNameAware > ApplicationContextAware > PostConstruct > ApplicationRunner > CommandLineRunner

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值