Spring Boot项目启动时执行指定的方法

项目场景:

本文介绍Spring Boot项目启动时执行指定的方法两种常用方式和他们之间的区别。


实现方案:

方式一:使用注解@PostConstruct

java 复制代码
@Component
public class PostConstructTest {
    @PostConstruct
    public void postConstruct() {
		System.out.println("启动时自动执行  @PostConstruct 注解方法");
    }
}

优点: 简单方便,加上一个注解就行了。

缺点:如果@PostConstruct方法内的逻辑处理时间较长,就会增加SpringBoot应用初始化Bean的时间,进而增加应用启动的时间。因为只有在Bean初始化完成后,SpringBoot应用才会打开端口提供服务,所以在此之前,应用不可访问。

建议:轻量的逻辑可放在Bean的@PostConstruct方法中,耗时长的逻辑如果放在@PostConstruct方法中,可使用@Async异步方法。

使用异步代码示例:

java 复制代码
@Service
public class TestService {
 
    @Async("testAsync")  //指定线程池
    public void test() {
        System.out.println("------------------------异步方法开始 " + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----------------异步方法执行完了" + Thread.currentThread().getName());
    }
}
java 复制代码
@Component
public class PostConstructTest {

	@Autowired
    private TestService testService;
	
    @PostConstruct
    public void postConstruct() {
		System.out.println("启动时自动执行  @PostConstruct 注解方法");
		testService.test();
    }
}

Spring Boot中多个PostConstruct注解执行顺序控制_多个postconstruct执行顺序-CSDN博客


方式二:实现CommandLineRunner接口

java 复制代码
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
		System.out.println("启动时自动执行 CommandLineRunner 的 run 方法");
    }
}

优点: 项目已经初始化完毕,才会执行方法,所以不用等这个方法执行完,就可以正常提供服务了。

缺点:暂未发现。

相关推荐
seventeennnnn27 分钟前
谢飞机的Java高级开发面试:从Spring Boot到分布式架构的蜕变之旅
spring boot·微服务架构·java面试·分布式系统·电商支付
超级小忍2 小时前
服务端向客户端主动推送数据的几种方法(Spring Boot 环境)
java·spring boot·后端
时间会给答案scidag2 小时前
报错 400 和405解决方案
vue.js·spring boot
Wyc724093 小时前
SpringBoot
java·spring boot·spring
ladymorgana4 小时前
【Spring Boot】HikariCP 连接池 YAML 配置详解
spring boot·后端·mysql·连接池·hikaricp
GJCTYU6 小时前
spring中@Transactional注解和事务的实战理解附代码
数据库·spring boot·后端·spring·oracle·mybatis
风象南7 小时前
SpringBoot敏感配置项加密与解密实战
java·spring boot·后端
写不出来就跑路8 小时前
暑期实习感悟与经验分享:从校园到职场的成长之路
java·开发语言·经验分享·spring boot
程序员张312 小时前
Maven编译和打包插件
java·spring boot·maven
灵犀学长14 小时前
EasyExcel之SheetWriteHandler:解锁Excel写入的高阶玩法
spring boot·excel