美文网首页
SpringBoot启动时,执行初始化方法的几种方式

SpringBoot启动时,执行初始化方法的几种方式

作者: js_hz | 来源:发表于2020-05-31 12:58 被阅读0次

    SpringBoot启动时,执行初始化方法的几种方式:

    方法1:CommandLineRunner接口
    import org.springframework.boot.CommandLineRunner;

    @SpringBootApplication
    public class DemoApp implements CommandLineRunner {

    @Autowired
    WebAppConfig appConfig;
    
    /**
     * main method
     */
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class, args);
        System.out.println("DemoApp已启动");
        System.out.println("222");  //打印顺序
    }
    
    @Override
    public void run(String... args) throws Exception {
        System.out.println("111");  //打印顺序
        //可以使用注入的Bean
        System.out.println(appConfig.getKey());
    }
    

    }

    方法2:使用注解@PostConstruct
    @Configuration
    public class WebAppConfig {

    //初始化变量
    @PostConstruct
    public void postConstruct(){
        MsgUtils.DATA_PATH=oxpaycLib;
    }
    

    }

    方法3:使用注解@EventListener
    @Configuration
    public class WebAppConfig {

    //初始化变量
    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        MsgUtils.DATA_PATH=oxpaycLib;
    }
    

    }

    这几个方法比较简单够用其它方式就不多写了。

    相关文章

      网友评论

          本文标题:SpringBoot启动时,执行初始化方法的几种方式

          本文链接:https://www.haomeiwen.com/subject/pqilzhtx.html