Spring和SpringBoot项目初始化管理

本文详细介绍了Spring框架中几个重要的生命周期接口:InitializingBean、DisposableBean、ApplicationRunner和CommandLineRunner。解释了这些接口的作用及应用场景,例如如何在Bean初始化或销毁时执行特定任务。

Spring

  1. InitializingBean
void afterPropertiesSet() throws Exception;

Invoked by a BeanFactory after it has set all bean properties supplied

当bean中的参数都初始化完毕后调用此方法

  1. DisposableBean
/**
 * Interface to be implemented by beans that want to release resources
 * on destruction. A BeanFactory is supposed to invoke the destroy
 * method if it disposes a cached singleton. An application context
 * is supposed to dispose all of its singletons on close.
 *
 * <p>An alternative to implementing DisposableBean is specifying a custom
 * destroy-method, for example in an XML bean definition.
 * For a list of all bean lifecycle methods, see the BeanFactory javadocs.
 *
 * @author Juergen Hoeller
 * @since 12.08.2003
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
 * @see org.springframework.context.ConfigurableApplicationContext#close
 */
public interface DisposableBean {

	/**
	 * Invoked by a BeanFactory on destruction of a singleton.
	 * @throws Exception in case of shutdown errors.
	 * Exceptions will get logged but not rethrown to allow
	 * other beans to release their resources too.
	 */
	void destroy() throws Exception;

}

当bean销毁的时候调用,用来做一些release resource

springboot

  1. ApplicationRunner
/**
	 * Callback used to run the bean.
	 * @param args incoming application arguments
	 * @throws Exception on error
	 */
void run(ApplicationArguments args) throws Exception;

ApplicationArguments是SpringBoot中的一个接口,他的实现类是DefaultApplicationArguments

org.springframework.boot.DefaultApplicationArguments

org.springframework.boot.ApplicationArguments

Provides access to the arguments that were used to run a {@link SpringApplication}.

通过ApplicationArguments的注释可以看到通过ApplicationArguments获取SpringApplication启动的一些参数

  1. CommandLineRunner
/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
void run(String... args) throws Exception;

可以看出这两个接口的区别是run方法的参数,如果不需要获取SpringApplication的启动参数,可以直接使用CommandLineRunner

否者使用ApplicationRunner

总结

ApplicationRunner,CommandLineRunner是在容器初始化完毕后调用相应的方法

InitializingBean 在bean中的参数已经初始化完毕后调用afterPropertiesSet方法

转载于:https://my.oschina.net/kipeng/blog/1795101

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值