1、实现CommandLineRunner接口
实现CommandLineRunner接口,注意做初始化任务的类需要放在扫描路径下,使用@Component注入到spring容器中。
import com.zw.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;@Component
public class CacheInitListener implements CommandLineRunner {@Autowiredprivate StudentService studentService;@Overridepublic void run(String... args) throws Exception {System.out.println("****************************CommandLineRunner项目初始化执行开始****************************");String user = studentService.user();System.out.println(user);System.out.println("****************************CommandLineRunner项目初始化执行结束****************************");}
}
项目启动结果:
2、实现InitializingBean接口
实现InitializingBean接口,复写afterPropertiesSet方法。
详见:
https://blog.csdn.net/qq_34207422/article/details/107045660
3、通过@PostConstruct注解定义
详见:
https://blog.csdn.net/qq_34207422/article/details/107045660
学海无涯苦作舟!!!