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

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;

    }



}

 

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

 

Java使用OCR技术识别图形图像文本信息 电子商城 购物网站 功能与技术选型
微信公众号