springboot2 添加启动类

springboot项目添加启动类方式,本人之总结了以下几种:

添加启动类的目的:比如在项目启动的时候就初始化一些数据之类的

方式1:

1:实现 ServletContextListener  类

@Slf4j
public class UserTaskMock implements ServletContextListener {

    @Override
    public  void contextInitialized(ServletContextEvent sce) {
        log.info("我初始化啦");
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    }

    @Override
    public  void contextDestroyed(ServletContextEvent sce) {
        log.info("我销毁啦");
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

    }
}

2:采用java类方式注册bean。使用springboot注解:@Configuration,等同于老试xml配置注册bean:比如:

@Configuration
@Slf4j
public class MyUserListener {
    @Bean
    public ServletListenerRegistrationBean registrationBean (){
        ServletListenerRegistrationBean listenerRegistrationBean = new ServletListenerRegistrationBean();
        listenerRegistrationBean.setListener(new UserTaskMock());
        return listenerRegistrationBean;
    }
}

第一种方式结束,启动项目就可以看到效果了

第二种方式:直接实现spring 提供的CommandLineRunner 接口

@Component
@Slf4j
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
      log.info("我加载进来啦~~~~~~~~~~~~~~~~~~~~~~~~`");
        log.info("我加载进来啦~~~~~~~~~~~~~~~~~~~~~~~~`");
        log.info("我加载进来啦~~~~~~~~~~~~~~~~~~~~~~~~`");
        log.info("我加载进来啦~~~~~~~~~~~~~~~~~~~~~~~~`");

    }
}

 

PS:如果项目有web.xml配置文件的话,直接在web.xml中配置servlet监听器也可以

你可能感兴趣的:(springboot使用笔记)