关于java:Spring-Boot-启动时让方法自动执行的-4-种方法

作者:FOEVERYANG

起源:https://www.cnblogs.com/lsgsp…

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

接下来我率领大家一一解答

1、实现ServletContextAware接口并重写其setServletContext办法

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

留神:该办法会在填充完一般Bean的属性,然而还没有进行Bean的初始化之前执行

2、实现ServletContextListener接口

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

3、将要执行的办法所在的类交个spring容器扫描(@Component),并且在要执行的办法上增加@PostConstruct注解或者动态代码块执行

@Component
public class Test2 {
    //动态代码块会在依赖注入后主动执行,并优先执行
    static{
        System.out.println("---static--");
    }
    /**
     *  @Postcontruct’在依赖注入实现后主动调用
     */
    @PostConstruct
    public static void haha(){
        System.out.println("@Postcontruct’在依赖注入实现后主动调用");
    }
}

4、实现ApplicationRunner接口

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

5、实现CommandLineRunner接口

/**
 * 用于批示bean蕴含在SpringApplication中时应运行的接口。能够在同一应用程序上下文中定义多个commandlinerunner bean,并且能够应用有序接口或@order正文对其进行排序。
 * 如果须要拜访applicationArguments而不是原始字符串数组,请思考应用applicationrunner。
 * 
 */
@Override
public void run(String... ) throws Exception {
    System.out.println("CommandLineRunner的run办法");
}

学习了,你晓得几种?

近期热文举荐:

1.600+ 道 Java面试题及答案整顿(2021最新版)

2.终于靠开源我的项目弄到 IntelliJ IDEA 激活码了,真香!

3.阿里 Mock 工具正式开源,干掉市面上所有 Mock 工具!

4.Spring Cloud 2020.0.0 正式公布,全新颠覆性版本!

5.《Java开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞+转发哦!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理