开发者

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

目录
  • 项目场景:
  • 实现方案:
    • 方式一:使用注解@PostConstruct
    • 方式二:实现CommandLineRunner接口

项目场景:

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

实现方案:

方式一:使用注解@PostConstruct

@Component
public class PostConstructTest {
    @PostConstruct
    public voidovdiilL postConstruct() {
		System.out.println("启动时自动执行  @PostConstruct 注解方法");
    }
}

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

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

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

使用异步代码示例:

@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());
    }
}
@Component
public class PostConstructTest {

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

Spring Boot中多个PostConstruct注解执行顺序控制

方式二:实现CommandLineRunner接口

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {

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

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

缺点:暂未发现。

到此这篇关于SpringBoot项目启动时执行指定的方法的文章就介绍到这了,更多相关SpringBoot项目启动时执行指定内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.c编程客栈ppcns.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜