Springboot启动执⾏特定代码的⽅式汇总
⽬录
实现InitializingBean接⼝或使⽤@PostConstruct注解
实现ApplicationListener接⼝
实现CommandLineRunner或ApplicationRunner 接⼝
实现InitializingBean接⼝或使⽤@PostConstruct注解
实现InitializingBean如下
public class AnotherExampleBean implements InitializingBean {
@Override
public void afterPropertiesSet() {
// 做⼀些初始化的⼯作
}
}
官⽅对其的解释是这样的:实现这个接⼝会让这个bean的所有必要的属性都被容器注⼊后(依赖注⼊),再去执⾏afterPropertiesSet()⾥的⽅法。
笔者再⽤⼀个简单的例⼦去实际演⽰⼀下(注意:使⽤@PostConstruct和实现接⼝是等价的,可以⼆选⼀)
我们在init⽅法上使⽤了@PostConstruct注解,并且⽅法⾥使⽤到了Chicken类,⽽这个Chicken类是通过依赖注⼊来设置的,所以印证了官⽅说的话,会在依赖注⼊完以后才会调⽤@PostConstruct注解的⽅法。那为什么不在构造器⾥往List⾥⾯⽅Chicken类呢,因为容器调⽤构造器⽅法的时候,Chicken类还没被注⼊,所以要写在@PostConstruct注解的⽅法⾥。
// ⾸先声明⼀个实体类
@Data
public class Chicken {
private String name ;
}
// 将他注⼊容器
@Configuration
public class UserConfig {
@Bean
public Chicken putUser(){
Chicken chinken = new Chicken();
chinken.setName("普通鸡块");
spring boot原理和生命周期return chinken;
}
}
// 在family 类中调⽤注⼊chinken
@Component
public class Family {
@Resource
Chicken chicken;
public static List<String> names;
@PostConstruct
public void init(){
names.Name());
}
public Family() {
names = new LinkedList<>();
}
}
实现ApplicationListener接⼝
如果⼀个容器⾥的bean实现了ApplicationListener接⼝,那么在任何时候,如果有ApplicationEvent(事件)在ApplicationContext(容器)中被发布,该bean会收到通知,从⽽可以执⾏相应策略。
下⾯是Spring提供的⼏种常⽤的ApplicationEvent事件
事件名称解释
ContextRefreshedEvent当容器ApplicationContext容器正在初始化或refreshed时会发布这个事件。这⾥的初始化意味着所有的bean都被加载,并且有后置处理的bean都被检测到并激活了。
ContextStartedEvent当容器启动调⽤start()⽅法是会发布这个事件,这⾥的开始是所有⽣命周期的bean
都收到了⼀个开始的信号
ContextStoppedEvent当容器调⽤stop⽅法时会发布这个事件
举⼀个简单的例⼦,下⾯的代码我实现ApplicationListener接⼝并监听ContextRefreshedEvent事件,所以当springboot启动并且初始化完成后,就能执⾏下⾯的⽅法了。
@Component
@Slf4j
public class MenuManage implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//做⼀些事情
}
}
实现CommandLineRunner或ApplicationRunner 接⼝
实现了CommandLineRunner的bean会被springboot监测到,并在项⽬启动后执⾏run⽅法,如果有多个bean实现了CommandLineRunner接⼝,那么可以使⽤order注解来指定执⾏顺序。
@Order(2)
@Component
public class ServerStartedReport implements CommandLineRunner{
@Override
public void args) throws Exception {
//do something
}
}
⽽实现ApplicationRunner接⼝与实现CommandLineRunner的唯⼀不同是,后者接收的参数是main⽅法传进去的原始参数,⽽ApplicationRunner接收的参数是封装过原始参数的,可以通过参数名字name来获取指定的参数。
@Component
public class MyApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner:"+ Arrays.SourceArgs()));
System.out.println("getOptionNames:"+OptionNames());
System.out.println("getOptionValues:"+OptionValues("foo"));
System.out.println("getOptionValues:"+OptionValues("log"));
}
}
到此这篇关于Springboot启动执⾏特定代码的⼏种⽅式的⽂章就介绍到这了,更多相关Springboot启动执⾏代码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。