springboot启动初始化
springboot启动加载方式
sprongboot项目启动初始化加载方式
- ApplicationRunner与CommandLineRunner接口
- Spring Bean初始化的构造方法、PostConstruct、init-method、InitializingBean
1、ApplicationRunner与CommandLineRunner
如果需要在SpringApplication启动时执行一些特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式相同,都只提供单一的run方法,而且该方法仅在SpringApplication.run(…)完成之前调用,更准确的说是在构造SpringApplication实例完成之后调用run()的时候。
1.1、ApplicationRunner
@Component
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner");
}
}
1.2、CommandLineRunner
Order注解或者使用Ordered接口来指定调用顺序,@Order()中的值越小,优先级越高
@Component
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...");
}
}
2、Spring Bean初始化的构造方法、PostConstruct、init-method、InitializingBean
2.1、构造器注入
@Component
public class LogicInConstructorExampleBean {
private static final Logger LOG
= Logger.getLogger(LogicInConstructorExampleBean.class);
private final Environment environment;
@Autowired
public LogicInConstructorExampleBean(Environment environment) {
//environment实例已初始化
this.environment = environment;
LOG.info(Arrays.asList(environment.getDefaultProfiles()));
}
}
2.2、@PostConstruct
@PostConstruct注解的方法,会在构造方法之后执行
加载顺序:Constructor > @Autowired > @PostConstruct > 静态方法
@Component
public class PostConstructExampleBean {
private static final Logger LOG
= Logger.getLogger(PostConstructExampleBean.class);
@Autowired
private Environment environment;
@PostConstruct
public void init() {
//environment 已经注入
LOG.info(Arrays.asList(environment.getDefaultProfiles()));
}
}
2.3、InitializingBean
Bean在实例化的过程中执执行顺序为:Constructor > @PostConstruct > InitializingBean > init-method
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet()方法。在spring初始化bean的时候,如果bean实现了InitializingBean接口,在对象的所有属性被初始化后之后才会调用afterPropertiesSet()方法。spring初始化bean肯定会在ApplicationRunner和CommandLineRunner接口调用之前
@Component
public class InitialingzingBeanTest implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean..");
}
}
尽管使用initialingBean接口可以实现初始化动作,但是官方并不建议我们使用InitializingBean接口,因为它将你的代码耦合在Spring代码中,官方的建议是在bean的配置文件指定init-method方法,或者在@Bean中设置init-method属性。
2.4、@Bean initMethod方法
@Bean(initMethod="init")
public InitMethodExampleBean exBean() {
return new InitMethodExampleBean();
}
public class InitMethodExampleBean {
private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class);
@Autowired
private Environment environment;
public void init() {
LOG.info(Arrays.asList(environment.getDefaultProfiles()));
}
}
初始化加载顺序:
- 构造器方法
- @PostConstruct 注解方法
- InitializingBean的afterPropertiesSet()
- Bean定义的initMethod属性方法
更多推荐
所有评论(0)