springboot項目啓動自動執行

springboot初始化

方式一.實現ApplicationRunner/CommandLineRunner 接口

@Order(value = 1) // 項目啓動運行方法的順序,從小到大
@Component
public class StartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("Start");
    }
}

方式二.@PostConstruct註解

// 帶有此註解的類在項目啓動時會自動註冊在spring容器
@Service 
public class RedisLockInit {
    @PostConstruct
    public void run(){
       System.out.println("Start");
    }
}

被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之後執行, init()方法之前執行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章