【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() + "缓存================================================");
		
	}
	
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值