Spring的refresh方法-SmartInitializingSingleton番外篇(5

所有的内容都是基于 https://gitee.com/chris_777/spring-boot2.1.3 springboot 源码
main函数入口org.springframework.boot.tests.hibernate52.Hibernate52Application.main


SmartInitializingSingleton是一个接口,在将所有的非懒加载的Bean注入到Spring容器之后,我们可以实现该接口,织入我们自己的逻辑。先看一下接口的源码吧。
该接口只有一个方法,根据方法名就能看出来基本的意思了,我们来实践一下吧。

1
2
3
4
5
6
7
8
public interface SmartInitializingSingleton {

/**
* 在所有非懒加载对象初始化之后调用
*/
void afterSingletonsInstantiated();

}

接口的调用入口
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean方法中的
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
//判断Bean是否为InitializingBean类型
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
//.......省略代码
}

新建MySmartInitializingSingletonTest类并实现SmartInitializingSingleton接口,实现BeanFactoryAware接口只是想获取当前上下文的BeanFactory测试用。
启动成功正常情况下会执行
org.springframework.boot.tests.hibernate52.mytest.custombean.ManualRegisterBean#onAfterSingletonsInstantiated 方法内的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Component
public class MySmartInitializingSingletonTest implements SmartInitializingSingleton, BeanFactoryAware {

private BeanFactory beanFactory;

@Override
public void afterSingletonsInstantiated() {
ManualRegisterBean manualRegisterBean = (ManualRegisterBean) beanFactory.getBean(ManualRegisterBean.class.getName());
manualRegisterBean.onAfterSingletonsInstantiated();
}


/**
* 在对象进行初始化操作的时候,可以获取到当前的bean工厂
* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods(java.lang.String, java.lang.Object)
* <p>
*
* @param beanFactory
* @throws BeansException
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
//自定义注解,自定义扫描。
//在 Spring的refresh方法-ApplicationListener番外篇(4 有说明
@Chris
public class ManualRegisterBean {


public void onContextRefreshedEvent() {
System.out.println("ContextRefreshedEvent>>>>>>>");
}

public void onAfterSingletonsInstantiated() {
System.out.println("afterSingletonsInstantiated>>>>>>>");
}
}
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

请我喝杯咖啡吧~

支付宝
微信