一次Spring Bean初始化顺序问题排查记录
最近在使用Springboot的时候需要通过静态的方法获取到Spring容器托管的bean对象,参照一些博文里写的,新建了个类,并实现ApplicationContextAware接口。代码大致如下:
@Component
public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
}
}
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
然后另外一个bean需要依赖这个静态获取bean的方法,代码大致如下:
@Component
public class TestBean{ private Object dependencyBean = SpringUtils.getBean(OtherBean.class); }
(注: 忽略代码逻辑是否合理~~ 这些代码是为演示所用简化的逻辑,肯定有同学会说:既然都是bean了为什么不注入,而是要用静态的获取呢?这个暂时不考虑,暂认为就必须要这样搞)
这两个类的层次结构和包名大致如下:
utils
> notice
> TestBean
> SpringUtils
就是TestBean在SpringUtils的下一级,TestBean所在包名为notice(这这个名字很重要! 直接影响到这两个bean的加载顺序,具体原理往下看)
代码就这么多,从以上代码来静态分析看,确实有些漏洞,因为没有考虑到Spring bean的加载顺序,可能导致的SpringUtils报空指针异常(在TestBean先于SpringUtils初始化的场景下),不管怎么样先执行一下看下效果,效果如下:
macOS操作系统下代码正常
windows平台下代码空指针异常
为什么这还跟平台有关了呢?难道Spring bean的初始化顺序还跟平台有关?事实证明这个猜想是正确的。下面从Spring源代码里来找原因。
这里需要重点关注的类是 ConfigurationClassPostProcessor,这个类是干什么的?它从哪里来?如何实现bean的加载的?
在Spring里可以指定甚至自定义多个BeanFactoryPostProcessor来实现在实例化bean之前做一些bean容器的更新操作,比如修改某些bean的定义、增加一些bean、删除一些bean等,而ConfigurationClassPostProcessor就是Spring为了支持基于注解bean的功能而实现的BeanFactoryPostProcessor。
web环境的Springboot默认使用的应用上下文(ApplicationContext,BeanFactoryPostProcessor就是注册到这里才会起作用的)是AnnotationConfigEmbeddedWebApplicationContext,在AnnotationConfigEmbeddedWebApplicationContext的构造方法里初始化this.reader的时候,在reader的构造方法里把ConfigurationClassPostProcessor添加到ApplicationContext里了:
public class AnnotationConfigEmbeddedWebApplicationContext
extends EmbeddedWebApplicationContext { private final AnnotatedBeanDefinitionReader reader; private final ClassPathBeanDefinitionScanner scanner; private Class<?>[] annotatedClasses; private String[] basePackages; /**
* Create a new {@link AnnotationConfigEmbeddedWebApplicationContext} that needs to be
* populated through {@link #register} calls and then manually {@linkplain #refresh
* refreshed}.
*/
public AnnotationConfigEmbeddedWebApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this); // 重点关注这句
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public class AnnotatedBeanDefinitionReader {
private final BeanDefinitionRegistry registry;
private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private ConditionEvaluator conditionEvaluator;
/**
* Create a new {@code AnnotatedBeanDefinitionReader} for the given registry and using
* the given {@link Environment}.
* @param registry the {@code BeanFactory} to load bean definitions into,
* in the form of a {@code BeanDefinitionRegistry}
* @param environment the {@code Environment} to use when evaluating bean definition
* profiles.
* @since 3.1
*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); // 这里把ConfigurationClassPostProcessor注册到上下文里了
}
上面介绍了Spring如何注册这个ConfigurationClassPostProcessor,下面看下这个类如何实现bean定义加载的。
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
// ....
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
do {
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses());
主要的代码是 parser.parse(candidates); 这句,当执行到这里的时候candidates已经包含Springboot的配置类,这个parse会根据配置类里定义的basePackge递归扫描这个目录下面的class文件(如果没有定义basePackage字段则把配置类所在的包作为basePackage),debug跟踪代码到最底层可以看到使用的是PathMatchingResourcePatternResolver的doRetrieveMatchingFiles方法:
protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Searching directory [" + dir.getAbsolutePath() +
"] for files matching pattern [" + fullPattern + "]");
}
File[] dirContents = dir.listFiles();
if (dirContents == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
}
return;
}
Arrays.sort(dirContents);
for (File content : dirContents) {
String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
if (!content.canRead()) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping subdirectory [" + dir.getAbsolutePath() +
"] because the application is not allowed to read the directory");
}
}
else {
doRetrieveMatchingFiles(fullPattern, content, result);
}
}
if (getPathMatcher().match(fullPattern, currPath)) {
result.add(content);
}
}
}
在这里可以看到有句 Arrays.sort(dirContents); 这个代码,就是在遍历一个文件夹下的资源时(包括文件夹和class文件),会先把资源排序一下,这个排序决定了bean的加载顺序!
那再看下File(上面代码中的dirContents是File列表)是如何排序的:
public class File
implements Serializable, Comparable<File>
{ /**
* The FileSystem object representing the platform's local file system.
*/
private static final FileSystem fs = DefaultFileSystem.getFileSystem(); /* -- Basic infrastructure -- */ /**
* Compares two abstract pathnames lexicographically. The ordering
* defined by this method depends upon the underlying system. On UNIX
* systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows
* systems it is not.
*
* @param pathname The abstract pathname to be compared to this abstract
* pathname
*
* @return Zero if the argument is equal to this abstract pathname, a
* value less than zero if this abstract pathname is
* lexicographically less than the argument, or a value greater
* than zero if this abstract pathname is lexicographically
* greater than the argument
*
* @since 1.2
*/
public int compareTo(File pathname) {
return fs.compare(this, pathname);
}
使用的是FileSystem的排序方法,再看看DefaultFileSystem.getFileSystem();拿到是是什么:
mac下:
/**
*
* @since 1.8
*/
class DefaultFileSystem { /**
* Return the FileSystem object for Unix-based platform.
*/
public static FileSystem getFileSystem() {
return new UnixFileSystem();
}
}
// UnixFileSystem
class UnixFileSystem extends FileSystem {
/* -- Basic infrastructure -- */
public int compare(File f1, File f2) {
return f1.getPath().compareTo(f2.getPath());
}
}
windows下:
/**
*
* @since 1.8
*/
class DefaultFileSystem { /**
* Return the FileSystem object for Windows platform.
*/
public static FileSystem getFileSystem() {
return new WinNTFileSystem();
}
}
//WinNTFileSystem
@Override
public int compare(File f1, File f2) {
return f1.getPath().compareToIgnoreCase(f2.getPath());
}
由于windows下和mac下使用的FileSystem不同,jdk windows版FileSystem实现的compare方法在比较文件是忽略了文件名的大小写,而mac版没有忽略大小写,所以导致前面提出的同样的代码在windows下报错,在mac下就是正常的问题。
但是为什么会有这样的差别呢?不是太明白为什么
那还剩最后一个问题,这个问题如何解决呢?我这有两个方法,一是修改类名让被依赖的类排在前面,这种方法不是太优雅,而且如果以后jdk更新了排序方法可能还会出bug,第二种是在使用类上加DependOn注解,主动说明在初始化使用类时首先加载被依赖的类,这样就没有问题了,但是我感觉在开发的时候尽量避免这种依赖问题,这让容器和业务代码参杂,以后维护是个噩梦
一次Spring Bean初始化顺序问题排查记录的更多相关文章
- spring bean初始化顺序
转载:http://blog.csdn.net/heyutao007/article/details/50326793 常用的设定方式有以下三种:通过实现 InitializingBean/Dispo ...
- Spring Bean初始化之后执行指定方法
转: Spring Bean初始化之后执行指定方法 2017年07月31日 15:59:33 vircens 阅读数:24807 Spring Bean初始化之后执行指定方法 在运用Spring进 ...
- spring bean初始化和销毁
spring bean的创建与消亡由spring容器进行管理,除了使用<bean><property/></bean>进行简单的属性配置之外,spring支持更人性 ...
- spring bean初始化及销毁你必须要掌握的回调方法
spring bean在初始化和销毁的时候我们可以触发一些自定义的回调操作. 初始化的时候实现的方法 1.通过java提供的@PostConstruct注解: 2.通过实现spring提供的Initi ...
- 🙈羞,Spring Bean 初始化/销毁竟然有这么多姿势
文章来源:http://1t.click/bfHN 一.前言 日常开发过程有时需要在应用启动之后加载某些资源,或者在应用关闭之前释放资源.Spring 框架提供相关功能,围绕 Spring Bean ...
- Spring bean初始化以及管理
在完成bean实例化后,spring会根据配置文件的设定情况对bean 的属性进行初始化, 1.autowire方式 (可查找自动装配对象 但bean中要有相应属性的set方法)这是一个自动装配的机制 ...
- Spring bean 初始化失败
在一个*context.xml 配置文件 A 中, 有个定义的bean B, 把 A 添加到 application-context.xml 中,发现B不能正常初始化. 解决办法: 添加 <co ...
- 阿里面试官:小伙子,你给我说一下Spring Bean初始化的几种常规方式吧
前言 通过构造方法实例化通过静态工厂实例化通过实例工厂实例化通过FactoryBean实例化 RumenzA实体类 package com.rumenz; public class RumenzA { ...
- Spring bean初始化
随机推荐
- [物理学与PDEs]第2章习题12 严格凸性的转换
设 $L=L(\xi_0,\xi_1,\cdots,\xi_n)$ 关于变量 $\xi_0>0,\xi_1,\cdots,\xi_n$ 为严格凸的. 证明函数 $$\bex M=\cfrac{1 ...
- 使用sessionStorage、localStorage存储数组与对象
先介绍一下localStorage localStorage对象是HTML5的客户端存储持久化数据的方案.为了能访问到同一个localStorage对象,页面必须来自同一个域名(子域名无效),使用同一 ...
- updateXML 注入 python 脚本
用SLQMAP来跑updateXML注入发现拦截关键字,然后内联注入能绕,最后修改halfversionedmorekeywords.py脚本,结果SQLMAP还是跑不出来.>_< hal ...
- java(9)类和对象
一.理解什么是类和对象 万事万物皆对象 1.1.属性——对象具有的特征(特点) 1.2.方法——对象可执行的操作(能干什么事) 1.3.对象的定义: 是一个客观存在的,看的见或摸得着的实体,由属性和方 ...
- AC自动机算法详解 (转载)
首先简要介绍一下AC自动机:Aho-Corasick automation,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法之一.一个常见的例子就是给出n个单词,再给出一段包含m个字符的文章, ...
- elk搭建日志系统
参考:https://www.cnblogs.com/yuhuLin/p/7018858.html 以上这篇文章已经写的很好很全了,之所以再自己写一遍大概就是记录一下,以后可能会有用吧 安装elast ...
- vlan 知识学习
背景 有人反映打印机总是提示ip冲突,经检查,打印机虽然设置了固定ip,但是所有员工在路由器都是设置了DHCP,所以会存在员工占用打印机IP 情况,在路由器添加某一段的ip不自动分配解决此问题 ...
- zabbix批量监控域名下nginx的访问50x状态码数量
背景: 购物车相关的站点某些页面经常出现502,如果超过一些阈值则需要报警给管理员知道 .自动发现脚本的编写 # vim /usr/local/zabbix_agents_3.2.0/scripts/ ...
- java 网站用户在线和客服聊天
注:本文来源于<java 网站用户在线和客服聊天> 这是应用到项目中的一个例子. 实现原理是将信息存储到Application域里面.然后使用Struts2 Action 用json格式的 ...
- 滑动时候报错:Unable to preventDefault inside passive event listener, 移动端滑动性能优化
https://www.jianshu.com/p/04bf173826aa 记录下 这篇帖子 解决办法1: 在touch的事件监听方法上绑定第三个参数{ passive: false }, 通过传 ...