springboot项目启动时自动执行方法
@PostConstruct方式
package com.xl.test.springtest.postconstruct;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
@Component
public class MyPostConstruct {
// @Autowired
// private DeptInfService deptInfService; //依赖注入
@PostConstruct
public void postMethod() {
System.out.println(new Date() + " : 正在执行@PostConstruct注解的方法。。。。。。。。。。。。。。。");
}
public MyPostConstruct() {
System.out.println(new Date() + " : 构造函数正在执行。。。。。。。。。。。。。。。");
}
}
实现ApplicationRunner接口
package com.xl.test.springtest.cloud;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
System.out.println("++++++++ApplicationRunner IS RUNNING...");
}
}
测试
直接运行springboot项目
实现CommandLineRunner
参见:https://blog.csdn.net/qinshengfei/article/details/114856010
类似的启动时执行方法
@Scheduled 自启动之后开始按照设置的时间周期性地执行
package com.omomcam.relayserver.utils;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.omomcam.relayserver.entity.TokenResp;
import lombok.Data;
/**
* @description 缓存accessToken
* @author Michael Corleone
* @date 2021年12月20日
* @version 1.0.0
*/
@Configuration
@EnableScheduling
@Data
public class CaAccessTokenUtil {
@Scheduled(fixedRate=14100000) // 每隔3小时55分钟,调用一次该方法。 14100000单位为毫秒。
public void sche() {
logger.info(new Date() + "缓存================================================");
}
}