内容
介绍部分ioc中的接口功能及其使用场景
apis
SmartInitializingSingleton
所有单例bean初始化完成后调用
类注释
- Callback interface triggered at the end of the singleton pre-instantiation phase
- during {@link BeanFactory} bootstrap. This interface can be implemented by
- singleton beans in order to perform some initialization after the regular
- singleton instantiation algorithm, avoiding side effects with accidental early
- initialization (e.g. from {@link ListableBeanFactory#getBeansOfType} calls).
- In that sense, it is an alternative to {@link InitializingBean} which gets
- triggered right at the end of a bean’s local construction phase.
This callback variant is somewhat similar to
- {@link org.springframework.context.event.ContextRefreshedEvent} but doesn’t
- require an implementation of {@link org.springframework.context.ApplicationListener},
- with no need to filter context references across a context hierarchy etc.
- It also implies a more minimal dependency on just the {@code beans} package
- and is being honored by standalone {@link ListableBeanFactory} implementations,
- not just in an {@link org.springframework.context.ApplicationContext} environment.
NOTE: If you intend to start/manage asynchronous tasks, preferably
- implement {@link org.springframework.context.Lifecycle} instead which offers
- a richer model for runtime management and allows for phased startup/shutdown.
方法注释
- Invoked right at the end of the singleton pre-instantiation phase,
- with a guarantee that all regular singleton beans have been created
- already. {@link ListableBeanFactory#getBeansOfType} calls within
- this method won’t trigger accidental side effects during bootstrap.
NOTE: This callback won't be triggered for singleton beans
- lazily initialized on demand after {@link BeanFactory} bootstrap,
- and not for any other bean scope either. Carefully use it for beans
- with the intended bootstrap semantics only.
调用过程
ApplicationContext
在 refresh
过程中会调用 finishBeanFactoryInitialization(beanFactory)
来提前初始化单例bean,具体方法是调用 preInstantiateSingletons
,
该方法定义在接口 ConfigurableListableBeanFactory
中。
1 | public void preInstantiateSingletons() throws BeansException { |
场景及实例
spring boot rocketmq中,ListenerContainerConfiguration
实现ApplicationContextAware, SmartInitializingSingleton
两个接口,将MQListenerContainer注册到了spring中