zoukankan      html  css  js  c++  java
  • SpringBoot启动时行初始化方法

    有时需要在SpringBoot启动时进行一些初始化的操作,有以下几种方法:

    1.实现CommandLineRunner接口

    在启动类上实现CommandLineRunner接口,重写run方法

    package com.zxh;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    
    @SpringBootApplication
    @Slf4j
    public class GatewayApplication implements CommandLineRunner {
        public static void main(String[] args) {
            SpringApplication.run(GatewayApplication.class, args);
        }
    
    
        @Value("${server.port}")
        private String port;
    
        @Override
        public void run(String... args) throws Exception {
            log.info("系统初始化中。。。。。");
            log.info("端口号: {}", port);
        }
    }

    2.使用注解@PostConstruct

    新建一个配置类,在要进行初始化的方法上加注解@PostConstruct:

    package com.zxh.config;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    
    import javax.annotation.PostConstruct;
    
    /**
     * 系统初始化操作
     */
    @Configuration
    @Slf4j
    public class WebAppConfig {
    
        @Value("${server.port}")
        private String port;
    
        @PostConstruct
        public void initRun() {
            log.info("系统初始化中。。。。。");
            log.info("端口号: {}", port);
        }
    
    }

    3.使用注解@EventListener

    package com.zxh.config;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.event.ContextRefreshedEvent;
    import org.springframework.context.event.EventListener;
    
    
    /**
     * 系统初始化操作
     */
    @Configuration
    @Slf4j
    public class WebAppConfig {
    
        @Value("${server.port}")
        private String port;
    
    
        @EventListener
        public void initRun(ContextRefreshedEvent event) {
            log.info("系统初始化中。。。。。");
            log.info("端口号: {}", port);
        }
    
    }

    上述的几种方法任选一种即可。

    就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
  • 相关阅读:
    Ninject依赖注入——构造函数、属性、方法和字段的注入
    轻量级IOC框架:Ninject
    WCF 服务端异常封装
    Tomcat远程调试和加入JMS(转)
    关于与产品相关的品牌、国藉等与产品质量的一些思考(转)
    eclipse及Java常用问题及解决办法汇总
    SourceInsight
    java.util.Timer分析源码了解原理
    WebSocket初探
    JAVA布局管理器
  • 原文地址:https://www.cnblogs.com/zys2019/p/15246202.html
Copyright © 2011-2022 走看看