SpringBoot启动时让方法自动执行的几种实现方式

在SpringBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个方法,那么实现提前加载的方式有哪些呢?

实现ServletContextAware接口并重写其setServletContext方法

@Component
public class TestStarted implements ServletContextAware {
    /**
     * 在填充普通bean属性之后但在初始化之前调用
     * 类似于initializingbean的afterpropertiesset或自定义init方法的回调
     *
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("setServletContext方法");
    }
}

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

实现ServletContextListener接口

/**
 * 在初始化Web应用程序中的任何过滤器或Servlet之前,将通知所有servletContextListener上下文初始化
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    //ServletContext servletContext = sce.getServletContext();
    System.out.println("执行contextInitialized方法");
}

@PostConstruct注解或者静态代码块

将要执行的方法所在的类交个Spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行

@Component
public class Test2 {
    //静态代码块会在依赖注入后自动执行,并优先执行
    static {
        System.out.println("---static--");
    }

    /**
     * @Postcontruct在依赖注入完成后自动调用
     */
    @PostConstruct
    public static void haha() {
        System.out.println("@Postcontruct在依赖注入完成后自动调用");
    }
}

实现ApplicationRunner接口

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

实现CommandLineRunner接口

/**
 * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个CommandLineRunner bean,并且可以使用有序接口或`@order`注释对其进行排序
 * 如果需要访问ApplicationArguments而不是原始字符串数组,请考虑使用ApplicationRunner
 */
@Override
public void run(String... ) throws Exception {
    System.out.println("CommandLineRunner的run方法");
}
上一篇 SpringBoot+Redis布隆过滤器防恶意流量击穿缓存
下一篇 Nginx禁用TLS1.0和TLS1.1使网站更安全
目录
文章列表
1 微信小程序异步与同步获取本地缓存及其调用注意
微信小程序异步与同步获取本地缓存及其调用注意
2
发布开源库到JCenter
发布开源库到JCenter
3
Spring Cloud使用Nacos作为服务配置中心
Spring Cloud使用Nacos作为服务配置中心
4
RandomStringUtils工具类
RandomStringUtils工具类
5
Android接入Firebase推送不执行onMessageReceived方法
Android接入Firebase推送不执行onMessageReceived方法
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。