一、@PostConstruct 注解完成资源初始化操作
使用@PostConstruct注解完成资源初始化操作,但前提这些初始化操作不需要依赖于其它Spring beans 的初始划工作。
测试样例:
@PostConstruct
public void init(){
System.out.println("@PostConstruct初始化");
}
注意:1.只有一个非静态方法能是使用次注解。2.被注解的方法不得有任何参数。3.被注解的方法返回值必须为void。4.被注解方法不得抛出已检查异常。5.此方法只会被执行一次。
二、CommandLineRunner
定义初始化类MyCommandLineRunner,注册成Bean,添加@Component注解。实现CommandLineRunner接口,并实现它的run()方法,在run方法中实现初始化逻辑。
测试样例:
package test.ysj.controller;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("项目初始化---------------1&