首页 技术 正文
技术 2022年11月16日
0 收藏 889 点赞 5,129 浏览 963 个字

很多时候我们都会碰到需要在程序启动时去执行的方法,比如说去读取某个配置,预加载缓存,定时任务的初始化等。这里给出几种解决方案供大家参考。

1. 使用@PostConstruct注解

这个注解呢,可以在Spring加载这个类的时候执行一次。来看一下下方代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class Test { public Test(){
System.out.println("我最先执行");
} /**
*我第二个执行
*/
@Autowired
private T t; /**
*我第三个个执行
*/
@PostConstruct
private void init(){
//假装有代码
}
}

上方就是@PostConstruct注解的使用方法了,同时也表示了此类被加载时的执行顺序。

2. CommandLineRunner接口

使用CommandLineRunner接口类似于Main方法启动,可以接受一个字符串数组的命令行参数,来看一下实现

1
2
3
4
5
6
7
8
@Component
public class MyCommandLineRunner implements CommandLineRunner{ @Override
public void run(String... args) throws Exception{
//假装有代码
}
}

3. ApplicationRunner 接口

此种方式与实现CommandLineRunner接口的区别就是他的参数是ApplicationArguments

1
2
3
4
5
6
7
8
9
10
@Order(value = 1)
@Component
public class MyApplicationRunner implements ApplicationRunner{ @Override
public void run(ApplicationArguments args) throws Exception{
//假装有代码
}
}

我们可以看到,此类相比较于第二种方式还增加一个@Order注解,这个注解其实第二种方式也是能加的。

它的作用就是控制类的加载顺序,这个顺序是从小到大的。比如说启动时先去加载Order的value等于1的类,然后去加载等于2的类。

Java项目启动时执行指定方法的几种方式

本文出自http://zhixiang.org.cn,转载请保留。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291