SpringBoot---系统启动加载实现的几种方法

版权声明:本文为博主原创文章,转载请说明出处。 https://blog.csdn.net/weixin_43549578/article/details/84491875

1.CommandLineRunner 

通过实现接口 CommandLineRunner 来实现,来完成项目启动就加载所需要的资源。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyProjectRunner implements CommandLineRunner {
 
    @Override
    public void run(String... args) throws Exception {
       //TODO 业务逻辑
    }
 
}

多个 CommandLineRunner接口的实例,如果想改变他们的运行顺序可以在实现类上加入  @Order注解

@Order(value=2)

2.ApplicationRunner

通过实现接口 ApplicationRunner来实现,来完成项目启动就加载所需要的资源。

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class MyApplicationRunner implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("===MyApplicationRunner==="+ Arrays.asList(args.getSourceArgs()));
        System.out.println("===getOptionNames========"+args.getOptionNames());
        System.out.println("===getOptionValues======="+args.getOptionValues("foo"));
        System.out.println("==getOptionValues========"+args.getOptionValues("developer.name"));
    }
}

3.在过滤器(Filter)和 监听器(Listener)中加载初始化

Filter

import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
 
/**
 * 使用注解标注过滤器
 * @WebFilter将一个实现了javax.servlet.Filter接口的类定义为过滤器
 * 属性filterName声明过滤器的名称,可选
 * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
 */
@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {
 
    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("执行过滤操作");
        chain.doFilter(request, response);
    }
 
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器初始化");
    }
 
}

ServletContext监听器(Listener)文件

使用@WebListener注解,实现ServletContextListener接口

@WebListener
public class MyServletContextListener implements ServletContextListener {
 
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContex初始化");
        System.out.println(sce.getServletContext().getServerInfo());
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContex销毁");
    }
 
}

监听Session的创建与销毁

@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
 
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("Session 被创建");
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("ServletContex初始化");
    }
 
}

在启动主类上加入@ServletComponentScan 注解

4.在SpringBoot主启动类中嵌套加载初始操作代码

@SpringBootApplication
@EntityScan("com.xx.entity")
@EnableTransactionManagement
@EnableCaching
//@EnableAsync //开启异步
public class MaobcMain implements WebMvcConfigurer {

    private static final Logger logger= LoggerFactory.getLogger(MaobcMain.class);

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MaobcMain.class, args);
        String[] activeProfiles = run.getEnvironment().getActiveProfiles();
        Arrays.stream(activeProfiles).forEach(profile ->logger.warn("Spring Boot 使用profile为:{}",profile));
        SystemInit.init();
    }

}
public class SystemInit {
 
    /** 记录用户每次请求时间:key为userId,value为请求时间毫秒值 */
    private static Map<String, Object> requestTime = new HashMap<String, Object>();
 
    public static Map<String, Object> getRequestTime() {
        return requestTime;
    }
 
    /**
     * 系统初始化
     */
    public static void init() {
        //清空本地用户登陆信息缓存
        RedisUtils.delete(ERedisDomain.TOKEN_LOGIN_USER);
 
        //初始化ES连接池
        ESUtils.initClient();
 
        //启动系统主线程
        SystemThread thread = new SystemThread();
        thread.setDaemon(true);
        thread.start();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43549578/article/details/84491875