第18章 卷五 · 总装房 · 资源与类型转换
资源与类型转换「我叫 Resource 。你⼿上拿的是我发的号牌,不是货。 号牌永远发得出去——想知道箱⼦⾥到底有没有东⻄,你得⾃⼰开⼝问⼀句 exists() 。」
开场:两个谁都答不上来的问题在成器坊⻔⼝站上半天,你会看⻅两样东⻄反复进出。
⼀样是料单: classpath:beans.xml 、 file:/etc/app/keystore.p12 、 classpath*:META-INF/spring.factories 。都是字符串,都得变成"能读出字节的东⻄"。
另⼀样是读出来的字: server.port: 8080 ⾥那四个字符,最后要变成⼀个 int ; spring.mvc.async.request-timeout: 30s 要变成 Duration ;
@DateTimeFormat(pattern="yyyy-MM-dd") 底下那⾏⽂本要变成 LocalDate 。于是坊⻔⼝摆了两道⻔。外⻔取料,内⻔验身份。 前⾯⼗六章讲的所有事——图纸怎么读进来、器怎么造、壳怎么套——全都建在这两道⻔之上。它们平时没⼈看,出事时全场找不着北。
先问两个问题,这⼀章要回答的就是它们:
问题⼀: @ComponentScan("com.example") 是怎么"列出 com.example 包下所有的类"的?翻遍 JDK 你会发现——没有这个 API。 ClassLoader.getResource(name) 只能按精确名字取⼀样东⻄, ClassLoader.getResources(name) 也⼀样,只是能取到多份同名的。"列出某个包下所有⽂件"这件事,标准库从来没有提供过。 那 Spring 是怎么办到的?
问题⼆:⼀个纯 Spring(不带 Boot)的容器⾥, String → Integer 到底是谁转的?是 ConversionService 吗?
如果你答"是",这⼀章会告诉你:纯 Framework 容器⾥默认根本没有 ConversionService 。这条默认值,是"同样的代码在 Boot ⾥能跑、在纯 Spring ⾥报ConverterNotFoundException "这类灵异事件的总根源。
三条第⼀性约束把整章撑起来:
- JDK 没有统⼀的"资源"概念。 URL 表示不了 classpath 相对路径, File 只认默认⽂件系统, ClassLoader.getResource 对⽬录的返回值 JDK ⽂档⾥就没定义。
- JDK 没有统⼀的"类型转换"概念。 JavaBeans 的 PropertyEditor 只会 String ↔ Object ,⽽且有状态、⾮线程安全、没有泛型上下⽂。
3. 通配扫描在 jar ⾥是"没有 API 的"。 classpath*:com/**/*.xml 这项能⼒,是 Spring 拿 ClassLoader.getResources + JarFile.entries() + Files.walk()硬凑出来的,因此它天⽣不可移植、天⽣有边界条件。
Spring 在这三个"没有"上⾯各盖了⼀间房。房盖得漂亮,但地基是别⼈家的空地——这⼀章的暗礁,全从这⾥⻓出来。
⼀、号牌不是货// [framework] spring-core/src/main/java/org/springframework/core/io/Resource.java:59
public interface Resource extends InputStreamSource {/**
- Determine whether this resource actually exists in physical form.
* <p>This method performs a definitive existence check, whereas the
* existence of a {@code Resource} handle only guarantees a valid- descriptor handle.
*/
boolean exists();

做了什么:定义⼀个"描述符(descriptor)",不是内容。 new ClassPathResource("根本不存在的⽂件.txt") 永远构造成功,不抛异常、不检查、不碰磁盘。要知道真相,必须再问⼀句 exists() 。
为什么这么设计:因为图纸库⾥要存它。 BeanDefinition 会携带资源引⽤四处传递,容器启动时把每⼀份候选⽂件都读进内存是不可接受的。号牌轻、可复制、可⽐较、可延迟兑现——货重,只有真要⽤时才开箱。
这套接⼝在本基线(Framework 7.1)上⼀共⼗六个⽅法,其中三个值得单独记住:
⽅法 语义 备注
default boolean isFile() 默认 falsejavadoc 原话「conservatively false by default」——保守地说不。返回 true 也只是"建议",不保证getFile() ⼀定成功
default Path getFilePath()默认
getFile().toPath()@since 7.0 ,本基线新增。给 zipfs、jimfs 这类⾮默认 FileSystem 准备的更可靠出⼝default void
consumeContent(IOConsumer<InputStream>)回调式读内容 @since 7.1 ,本基线新增,是本章后⾯那出好戏的主⻆
⚠ 暗礁⼀: contentLength() 的默认实现会把整条流读空。
// [framework] spring-core/src/main/java/org/springframework/core/io/AbstractResource.java:154@Override
public long contentLength() throws IOException {
InputStream is = getInputStream();
try {
long size = 0;
byte[] buf = new byte[256];
int read;
while ((read = is.read(buf)) != -1) {
size += read;
}
return size;
}// ...256 字节⼀⼝、把整个⽂件嚼⼀遍,只为了数出它有多⻓。javadoc ⾃⼰在上⾯写着 "we strongly recommend overriding this method with a more optimal implementation"。
你⾃⼰写⼀个 Resource 忘了覆盖它,Web 层为了填 Content-Length 响应头调⼀次,流就空了——接下来给客户端写的是零字节,⽽且不报错。
⚠ 暗礁⼆: equals ⽐的是描述字符串,⽽且左侧判定放到了顶层接⼝。
// [framework] spring-core/src/main/java/org/springframework/core/io/AbstractResource.java:238@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof Resource that &&
getDescription().equals(that.getDescription())));
}注意判定是 instanceof Resource ——不是 instanceof AbstractResource ,更不是 getClass() 相等。于是两个毫不相⼲的实现类,只要描述串撞上就"相等"。⼦类⾥ClassPathResource 、 FileSystemResource 、 UrlResource 都各⾃覆盖了 equals ⽤规范化字段来⽐,但 ByteArrayResource 这类没覆盖的,仍旧⾛描述串。
这条为什么要紧?因为后⾯那个通配扫描器全程⽤ LinkedHashSet<Resource> 去重。整个 classpath*: 的结果集语义,直接架在这个 equals 上⾯。记住这⼀点,第六节会回来收账。
⼆、把四个世界伪装成同⼀套: AbstractFileResolvingResourceClassPathResource 和 UrlResource 最后都要落到⼀个 URL 上,⽽ URL 背后可能是本地⽂件、jar ⾥的⼀条 entry、⼀个 HTTP 地址、或者 JBoss 的虚拟⽂件系统。让上层看不出区别,是这个类唯⼀的活⼉。
看它的 exists() ⾥最有画⾯感的⼀段:
// [framework] spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java:61
HttpURLConnection httpCon = (con instanceof HttpURLConnection huc ? huc : null);
if (httpCon != null) {
httpCon.setRequestMethod("HEAD");
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
return true;
}
else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
else if (code == HttpURLConnection.HTTP_BAD_METHOD) {
con = url.openConnection();
customizeConnection(con);// ...再来⼀次
}
}做了什么:为了回答"这东⻄存在吗",向远端发⼀个 HEAD 。遇到 405 Method Not Allowed ——有些⽼服务器压根不⽀持 HEAD——重开⼀条连接再试⼀次。
精妙在哪:这不是算法上的精妙,是⼆⼗年现场经验沉淀成的⼗⾏代码。同⼀个⽅法往下⾛⼏⾏,还有⼀段:
// [framework] spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java:86
if (con instanceof JarURLConnection jarCon) {// For JarURLConnection, do not check content-length but rather the
// existence of the entry (or the jar root in case of no entryName).
// getJarFile() called for enforced presence check of the jar file,
// throwing a NoSuchFileException otherwise (turned to false below).
JarFile jarFile = jarCon.getJarFile();
try {return (jarCon.getEntryName() == null || jarCon.getJarEntry() != null);
}
finally {
if (!jarCon.getUseCaches()) {
jarFile.close();
}
}
}jar ⾥的条⽬不能看 content-length——⼀个空⽂件⻓度是 0,但它确实存在。所以改看 entry 在不在。⽽ getJarFile() 那⼀句是故意调的,注释说得明⽩:为了强制触发⼀次存在性检查。
⚠ 暗礁三:jar 连接默认是开缓存的。
// [framework] spring-core/src/main/java/org/springframework/util/ResourceUtils.java:452
public static void useCachesIfNecessary(URLConnection con) {
if (!(con instanceof JarURLConnection)) {
con.setUseCaches(false);
}
}翻译成⼈话:⾮ jar 连接⼀律关缓存;jar 连接保持 JVM 默认(通常是 true )。 后果是 JVM 会把 JarFile 句柄缓存住——热部署时你换了 jar ⽂件,读到的还是旧内容;或
者句柄迟迟不释放,Windows 上⽂件删不掉。这就是 UrlResource#setUseCaches(boolean) 和 PathMatchingResourcePatternResolver#setUseCaches(boolean) 这两个开关存在的全部理由。
🦴 ⻣灰级细节: UrlResource 还顺⼿做了⼀件很多⼈不知道的事——从 URL 的 userinfo ⾥⾃动⽣成 HTTP Basic 认证头。
// [framework] spring-core/src/main/java/org/springframework/core/io/UrlResource.java:260
protected void customizeConnection(URLConnection con) throws IOException {
super.customizeConnection(con);
String userInfo = this.url.getUserInfo();
if (userInfo != null) {
String encodedCredentials = Base64.getUrlEncoder().encodeToString(userInfo.getBytes());
con.setRequestProperty(AUTHORIZATION, "Basic " + encodedCredentials);
}
}也就是说,配置⾥写 https://user:pass@host/config.yml ,密码会被⾃动 Base64 编进请求头发出去。⽅便,但这意味着⼀条明⽂⼝令躺在你的配置⽂件⾥,且没有任何地⽅提示你它会被这样使⽤。(另有⼀处细节:⽤的是 Base64.getUrlEncoder() ⽽⾮标准编码器。)
三、给 JDK 打补丁的那个 catchClassPathResource 内部藏着两个 path 字段:⽤户原样给的 path (⽤于 createRelative 和"相对某个类"的解析),和去掉前导斜杠的 absolutePath (因为ClassLoader 的资源⽅法不接受前导 / )。解析时三分岔:
// [framework] spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java:173
protected @Nullable URL resolveURL() {
try {
if (this.clazz != null) {
return this.clazz.getResource(this.path);
}
else if (this.classLoader != null) {
return this.classLoader.getResource(this.absolutePath);
}
else {
return ClassLoader.getSystemResource(this.absolutePath);
}
}
catch (IllegalArgumentException ex) {// Should not happen according to the JDK's contract:
// see https://github.com/openjdk/jdk/pull/2662
return null;
}
}看那个 catch 。按照 JDK 的契约,这个异常不该出现——注释⾥连 OpenJDK 的 PR 编号都给了。这是⼀间下级衙⻔给上级衙⻔的疏漏打的补丁:明知道上头写着"不会发⽣",还是接住了,因为现场真的发⽣过。
整个 core/io 包⾥这样的化⽯不⽌⼀处,后⾯第六节还有更⽼的。
四、唯⼀的⼀次性号牌⼗⼏个 Resource 实现⾥,只有⼀个的 isOpen() 返回 true :
// [framework] spring-core/src/main/java/org/springframework/core/io/InputStreamResource.java:141
public InputStream getInputStream() throws IOException, IllegalStateException {
if (this.read) {
throw new IllegalStateException("InputStream has already been read (possibly for early content length " +
"determination) - do not use InputStreamResource if a stream needs to be read multiple times");
}
this.read = true;
return this.inputStreamSource.getInputStream();
}它包着⼀条已经打开的流,只能读⼀次。异常消息⾥那句括号——"possibly for early content length determination"——就是第⼀节暗礁⼀的回声:很多⼈栽在这⾥,是因为某个中间层悄悄调了⼀次 contentLength() 。
⚠ 暗礁四,⽽且极其隐蔽。 类 javadoc ⾥有⼀句:
...this is particularly true when used with Spring's web resource rendering which specifically skips contentLength() for this exact class only."for this exact class only" —— Web 层是⽤精确类型判断绕开它的。所以你 extends InputStreamResource 写个⼦类,就不再享受这个豁免,流照样被读空。⼀个继承动作让⾏为静默改变,且没有任何编译期提示。
五、⼀个星号的官司这⼀节换个写法。以下是坊⾥收发房的⼀份案卷。
案由:两块牌⼦挨着挂,只差⼀个星号。
现场: DefaultResourceLoader 的⻔⼝,⼀共五岔路。
// [framework] spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java:155
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : getProtocolResolvers()) { //① 外挂 SPI优先
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) { //② 前导斜杠
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) { //③ classpath:
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else if (location.startsWith(CLASSPATH_ALL_URL_PREFIX)) { //④ classpath*:
return new ClassPathAllResource(location.substring(CLASSPATH_ALL_URL_PREFIX.length()), getClassLoader());
}
else {
try {
URL url = ResourceUtils.toURL(location); //⑤ 当 URL试试
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
return getResourceByPath(location); //⑥ 兜底:当裸路径
}
}
}争点⼀:③ 挂在 ④ 前⾯, classpath*: 会不会被 classpath: 那块牌⼦先吞掉?
裁定:不会。 "classpath*:x".startsWith("classpath:") 是 false ——第⼗个字符是 * 不是 : 。但这是靠字符恰好不同侥幸成⽴的,不是靠结构保证的。 看着惊险,实际安全。
争点⼆:④ 这⼀⽀在 Framework 6 时代根本不存在。
裁定属实,且是本基线的⼀处重要变化。 6.x ⾥ getResource("classpath*:foo.xml") 只会得到⼀个路径⾥带星号的普通 ClassPathResource , exists() ⼏乎必然为false ——⼀个静默的错误。7.1 做了两件事:把 CLASSPATH_ALL_URL_PREFIX 常量从 ResourcePatternResolver 上移到了 ResourceLoader ,并新增了ClassPathAllResource 。证据是源码 @since 标签⾃⼰写的:
// [framework] spring-core/src/main/java/org/springframework/core/io/ResourceLoader.java:60
* <p>As of Spring Framework 7.1, this prefix is supported for {@link #getResource}
* calls as well (exposing a multi-content resource handle), rather than just for
* {@link org.springframework.core.io.support.ResourcePatternResolver#getResources}.
* @since 7.1 (previously only declared on the
* {@link org.springframework.core.io.support.ResourcePatternResolver} sub-interface)争点三:⼀个句柄,怎么代表"散落在⼗⼏个 jar ⾥的⼗⼏份同名⽂件"?
证物:
// [framework] spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java:262
return switch (streams.size()) {
case 0 -> InputStream.nullInputStream();
case 1 -> streams.get(0);
default -> new SequenceInputStream(Collections.enumeration(streams));
};⽤ SequenceInputStream 把 N 本账⾸尾缝成⼀条流。 对 .properties 这种流⽔账,缝起来照念,天经地义;对 XML 这种每本都有封⽪的账册——必炸。三个 <?xml...?> 声明串成⼀串,任何解析器都会当场翻脸。
这就是 consumeContent 在 7.1 被发明出来的全部理由:不缝了,⼀本⼀本念。
// [framework] spring-core/src/main/java/org/springframework/core/io/DefaultResourceLoader.java:270
public void consumeContent(IOConsumer<InputStream> consumer) throws IOException {
ClassLoader cl = getClassLoader();
Enumeration<URL> urls = (cl != null ? cl.getResources(getPath()) : ClassLoader.getSystemResources(getPath()));
while (urls.hasMoreElements()) {
try (InputStream inputStream = urls.nextElement().openStream()) {
consumer.accept(inputStream);
}
}
}最硬的物证在调⽤⽅那边。XML 读取器改写成了这样:
// [framework] spring-beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java:342
AtomicInteger count = new AtomicInteger();
encodedResource.getResource().consumeContent(inputStream -> {
InputSource inputSource = new InputSource(inputStream);// ...
count.addAndGet(doLoadBeanDefinitions(inputSource, encodedResource.getResource()));
});
return count.get();那个 AtomicInteger 就是判决书。如果回调只会被调⼀次,根本不需要⼀个累加器。 它的存在本身,公开承认了"⼀个 Resource 句柄可能对应多份内容"这件事。同样的改写还发⽣在 YAML 处理器、Properties 读取器和 ReloadableResourceBundleMessageSource 上。
附带处罚: ClassPathAllResource 的 getURL() 被覆盖成恒抛 FileNotFoundException (消息⾥直接叫你改⽤ classpath: ),但 exists() 没有被覆盖——它继承⽗类,只看第⼀份。所以这块号牌上, exists() 可⽤、 getURL() 必炸。这是刻意的能⼒裁剪,但是⼀个不对称的裁剪,写代码时得记着。
案卷结。
六、 classpath*: 通配扫描:组件扫描的地基现在回到开场的问题⼀。这⼀节是本章最重的⼀节,因为 @ComponentScan 能⼯作,全靠它。
核⼼事实先摆出来
classpath*: 的"取全部"能⼒,100% 来⾃⼀个 JDK API: ClassLoader.getResources(name) 。// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:436
protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
Set<Resource> result = new LinkedHashSet<>(16);
ClassLoader cl = getClassLoader();
Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
while (resourceUrls.hasMoreElements()) {
URL url = resourceUrls.nextElement();
result.add(convertClassLoaderURL(url));
}
if (!StringUtils.hasLength(path)) {// The above result is likely to be incomplete, i.e. only containing file system references.// We need to have pointers to each of the jar files on the class path as well...
addAllClassLoaderJarRoots(cl, result);
}
return result;
}⽽ getResources 只接受精确名字。所有通配能⼒,都是围着这⼀个 API 现搭的脚⼿架。
四条岔路// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:365
public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
String locationPatternWithoutPrefix = locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length());// Search the module path first.
Set<Resource> resources = findAllModulePathResources(locationPatternWithoutPrefix);// Search the class path next.
if (getPathMatcher().isPattern(locationPatternWithoutPrefix)) {
Collections.addAll(resources, findPathMatchingResources(locationPattern));
}
else {
Collections.addAll(resources, findAllClassPathResources(locationPatternWithoutPrefix));
}
return resources.toArray(EMPTY_RESOURCE_ARRAY);
}
else {// Generally only look for a pattern after a prefix here,


// and on Tomcat only after the "*/" separator for its "war:" protocol.
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
locationPattern.indexOf(':') + 1);// ...模块路径先扫、类路径后扫( @since 6.0 ),结果丢进 Set 合并——第⼀节埋的账在这⾥结:去重完全依赖 Resource.equals 。
那个 war: 的特判是给 Tomcat 开的后⻔: war: 协议⽤ */ 当分隔符,分隔符⾃⼰含星号,不特判就会被当成通配符。
从右往左砍拿到 classpath*:com/example/**/*Config.class 这样⼀串,第⼀件事是把"确定的前缀"和"通配的后缀"劈开:
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:801
protected String determineRootDir(String location) {
int prefixEnd = location.indexOf(':') + 1;
int rootDirEnd = location.length();
while (rootDirEnd > prefixEnd && getPathMatcher().isPattern(location.substring(prefixEnd, rootDirEnd))) {
rootDirEnd = location.lastIndexOf('/', rootDirEnd - 2) + 1;
}
if (rootDirEnd == 0) {
rootDirEnd = prefixEnd;
}
return location.substring(0, rootDirEnd);
}从右往左,⼀段⼀段退,退到剩下的前缀不含通配为⽌。javadoc 举的例⼦最直⽩: /WEB-INF/*.xml 退出来的根⽬录是 /WEB-INF/ 。像⼀个⼈拿着⼀张写模糊了的地址,顺着路⼀路往回⾛,⾛到最后⼀个能确认的路⼝停下。
停下之后,对每个根⽬录分三路⾛:JBoss VFS ⼀路、jar ⼀路、⽂件系统⼀路。
jar ⾥:有序账册的快速翻⻚// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:886
for (String entryPath : entriesCache.tailSet(rootEntryPath, false)) {
if (!entryPath.startsWith(rootEntryPath)) {// We are beyond the potential matches in the current TreeSet.
break;
}
rootEntryPathFound = true;
String relativePath = entryPath.substring(rootEntryPath.length());
if (getPathMatcher().match(subPattern, relativePath)) {
result.add(rootDirResource.createRelative(relativePath));
}
}✨ 爽点:缓存存的不是 Set ⽽是 NavigableSet ( TreeSet )。 tailSet(rootEntryPath, false) 直接跳到前缀的起点,⼀旦发现条⽬不再以前缀开头就 break ——因
为有序集合保证后⾯不可能再有匹配。⼀个⼤ jar ⾥⼏万条 entry,扫⼀个包只碰其中⼀⼩段。⽤有序性换取 O(log n) 定位 + 提前终⽌,这⼀⼿很漂亮。
🦴 ⻣灰级细节:同⼀个⽅法⾥往下⼏⼗⾏,藏着这么⼀段——
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:953
if (StringUtils.hasLength(rootEntryPath) && !rootEntryPath.endsWith("/")) {// Root entry path must end with slash to allow for proper matching.// The Sun JRE does not return a slash here, but BEA JRockit does.
rootEntryPath = rootEntryPath + "/";
}BEA JRockit。 ⼀个 2008 年前后的 JVM,早已并⼊ Oracle 并停产。这⾏注释是化⽯,和类⾥那个⽤反射探测 OSGi Equinox FileLocator.resolve(URL) 的静态块⼀样,是 2000 年代应⽤服务器混战留在代码⾥的年轮。这就是"兼容性"的真实重量:它不是⼀句⼝号,是⼗⼏年前某个⼚商的⼀个斜杠,⾄今还占着你运⾏时的⼀次字符串判断。
⽂件系统⾥:⼀条被吞掉的异常// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:1092
try (Stream<Path> files = Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)) {
files.filter(isMatchingFile).sorted().map(FileSystemResource::new).forEach(result::add);
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to search in directory [%s] for files matching pattern [%s]: %s"
.formatted(rootPath.toAbsolutePath(), subPattern, ex));
}
}
return result;
}.sorted() 那⼀下是好事:⽂件系统的⽬录遍历顺序本身不保证,排⼀下序,扫描结果就稳定可复现了。
⚠ 暗礁五: FOLLOW_LINKS 会跟随符号链接。符号链接成环时 Files.walk 抛 FileSystemLoopException ——被这个 catch (Exception ex) 接住,降级成⼀条 warn
⽇志,然后 return result 。扫描就此静默地不完整。 你的应⽤少了⼀半 Bean,⽇志⾥只有⼀⾏ warn,⽽且是 warn 级别,⽣产上多半被过滤掉了。
两条路⾛到同⼀个⻔⼝,如何认出是同⼀个⼈// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:468
if (ResourceUtils.URL_PROTOCOL_FILE.equals(url.getProtocol())) {
try {// URI decoding for special characters such as spaces.
return new FileSystemResource(ResourceUtils.toURI(url).getSchemeSpecificPart());
}file 协议⼀律归⼀化成 FileSystemResource (javadoc 注明 as of 6.0.5)。理由写得很直⽩:要"matching the outcome of pattern-based class path traversal in the sameresource layout, as well as matching the outcome of module path searches"。
翻译过来:模块路径扫出来的那个⽂件,和类路径扫出来的那个⽂件,得能在 LinkedHashSet ⾥认出彼此是同⼀个⼈。⽽ FileSystemResource.equals ⽐的是路径串——所以只要两边都包成 FileSystemResource ,就⾃动去重了。模块侧也做了对称的转换。
这是⼀处很有分量的设计:⽤"统⼀表示"换取"⾃动去重",⽽不是写⼀个专⻔的⽐对函数。
官⽅⾃⼰写下的两条警告这⼀节最实⽤的东⻄,是 Spring ⾃⼰写在类 javadoc ⾥的两条 WARNING 。这不是我的推测,是官⽅原话:
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:173
* <p><b>WARNING:</b> Note that "{@code classpath*:}" when combined with- Ant-style patterns will only work reliably with at least one root directory
- before the pattern starts, unless the actual target files reside in the file
* system. This means that a pattern like "{@code classpath*:*.xml}" will
* <i>not</i> retrieve files from the root of jar files but rather only from the- root of expanded directories.
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:186
* <p><b>WARNING:</b> Ant-style patterns with "{@code classpath:}" resources are not- guaranteed to find matching resources if the base package to search is available
- in multiple class path locations.
两句⼈话:
- classpath*:*.xml 扫不到 jar 根——只能扫到解压⽬录的根。因为 ClassLoader.getResources("") 按 JDK 的⾏为只返回⽂件系统位置。
- classpath:com/**/*.xml 只扫第⼀份—— getResource("com") 返回的是"最近的"那⼀个 URL,如果 com 这个包在三个 jar ⾥都有,另外两个就被静默忽略了。这种情况请改⽤ classpath*: 。
这⼀章的批评点,就落在第 1 条的补救措施上。
Spring 为第 1 条准备了两道补救: addAllClassLoaderJarRoots 去内省类加载器,把 classpath 上每个 jar 的根都补进来;如果还不够, addClassPathManifestEntries去读 java.class.path 系统属性,再逐个 jar 打开读 Manifest 的 Class-Path 头。
问题在于:第⼀道补救只对 URLClassLoader 有效。⽽从 JDK 9 模块化之后,应⽤类加载器不再是 URLClassLoader 。也就是说,这条路在任何现代 JVM 上基本是空转的——它还在那⼉,只是不再命中了。于是才有了第⼆道补救:绕开类加载器,直接去读系统属性和 manifest ⽂本。
补救的补救,本身就是⼀份诊断书。 ⽽ Spring ⾃⼰在 javadoc ⾥对这⼀整套的定性是——
...tries to mitigate the jar root lookup limitation through URLClassLoader introspection and " java.class.path " manifest evaluation; however, without portabilityguarantees."without portability guarantees",官⽅⾃⼰写的。 这套被⽆数⼈当成理所当然的 classpath*: 通配扫描,在最关键的边界情形上,Spring 从未承诺过它能⼯作。它不是⼀个健壮的抽象,它是⼀堆在标准库缺⼝上打的、彼此叠加的补丁——⽽这堆补丁,恰恰是 @ComponentScan 的地基。
有趣的是,模块路径那边反⽽⼲净:
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java:1150附近
try (ModuleReader moduleReader = resolvedModule.reference().open();
Stream<String> names = moduleReader.list()) {
names.filter(resourcePatternMatches)ModuleReader.list() 是 JDK 官⽅给出的、唯⼀能"列出模块内全部资源名"的 API——正是 classpath 世界缺的那⼀个。所以在模块路径下, classpath*:*.xml 这种"jar根 + 通配"反⽽是可靠的。类 javadoc 也承认:"some of the limitations of class path searches may not apply when applications are deployed as modules."
JPMS 早在 2017 年就把这个洞补上了。只是⼆⼗多年积累下来的 classpath 世界,还得靠 BEA JRockit 那个斜杠继续撑着。
(另:这⾥两处 NativeDetector.inNativeImage() 分⽀直接跳过模块扫描——native image 下这条路⾛不通,这也是 AOT 路线上组件扫描要在构建期做完的原因之⼀。)
七、内⻔:为什么⾮要重造 PropertyEditor 这个轮⼦外⻔讲完,进内⻔。
JavaBeans 的 PropertyEditor 是 1997 年的东⻄,Spring ⼀开始就⽤它做属性绑定。到 3.0(2009)Spring 另起炉灶写了 core.convert 。为什么? 四条罪状:
PropertyEditor core.convert⽅向 只有 String ↔ Object , Integer → Long ⽆处安放 任意 S → T状态 有状态( setValue / getValue 就是⼀个可变槽位)→ ⾮线程安全,每次绑定都得 new ⼀份 ⽆状态、线程安全、可共享泛型上下⽂ ⽆。不知道⽬标是 List<Integer> 还是 List<String> TypeDescriptor 携带完整泛型注解上下⽂ ⽆。不知道字段上有没有 @DateTimeFormat TypeDescriptor 携带注解新体系分三层,外加⼀个正交维度:
Converter<S, T> :⼀对⼀,最常⽤, @FunctionalInterfaceConverterFactory<S, R> :⼀对"⼀族"(S → R 的所有⼦类),⽐如 String → 任意 Enum
GenericConverter :多对多,且能拿到 TypeDescriptorConditionalConverter :正交的第四维——上⾯三种都能叠加它,运⾏时再决定要不要匹配
⚠ 暗礁六,⾮常常⻅:
// [framework] spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java:85
public void addConverter(Converter<?, ?> converter) {
ResolvableType[] typeInfo = getRequiredTypeInfo(converter.getClass(), Converter.class);
if (typeInfo == null && converter instanceof DecoratingProxy decoratingProxy) {
typeInfo = getRequiredTypeInfo(decoratingProxy.getDecoratedClass(), Converter.class);
}
if (typeInfo == null) {
throw new IllegalArgumentException("Unable to determine source type <S> and target type <T> for your " +
"Converter [" + converter.getClass().getName() + "]; does the class parameterize those types?");
}⽤ lambda 写 Converter 再丢进 addConverter(Converter) ,直接抛异常。 因为 lambda 擦除后拿不到泛型实参。必须改⽤三参重载 addConverter(Class<S>,Class<T>, Converter) 把类型显式说出来。
顺便看那个 DecoratingProxy 分⽀——它是为"被 AOP 套了壳的 converter bean"准备的。壳把泛型信息挡住了,得从壳⾥问出被装饰的原类。全书的魂在这⾥⼜露了⼀次脸:
递到⼿上的常常不是原件,连注册转换器这种边⻆地⽅都得为它让路。
⼋、谁赢:双重层次循环 + 后注册者优先GenericConversionService 找转换器的算法,是整个体系的⼼脏:
// [framework] spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java:500附近
List<Class<?>> sourceCandidates = getClassHierarchy(sourceType.getType());
List<Class<?>> targetCandidates = getClassHierarchy(targetType.getType());
for (Class<?> sourceCandidate : sourceCandidates) {
for (Class<?> targetCandidate : targetCandidates) {
ConvertiblePair convertiblePair = new ConvertiblePair(sourceCandidate, targetCandidate);
GenericConverter converter = getRegisteredConverter(sourceType, targetType, convertiblePair);
if (converter != null) { return converter; }
}
}
return null;源类型层次 × ⽬标类型层次,双重循环。 层次表是 BFS ⽣成的:⾃身(基本类型先转包装)→ ⽗类(跳过 Object 和 Enum )→ 所有接⼝ → 枚举补 Enum → 最后追加Object (数组版排在⾮数组版前⾯)。命中的那⼀刻就返回,所以层次表的顺序就是优先级。
查不到具体 pair,才轮到 globalConverters ——那些 getConvertibleTypes() 返回 null 的条件转换器,只能靠 matches ⼀个个问过去。
⽽同⼀个 (S, T) 上注册了好⼏个转换器时,谁赢?
// [framework] spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java:612
private static class ConvertersForPair {
private final Deque<GenericConverter> converters = new ConcurrentLinkedDeque<>();
public void add(GenericConverter converter) {
this.converters.addFirst(converter);
}addFirst 。头插。后注册的赢。
这⼀⾏是本章第⼆值钱的结论,它直接解释了⼀个本基线⾥才出现的有趣现象。
✨ 爽点时刻:下沉不夺权。
Framework 7.1 把 DataSize 的转换器下沉进了公共层—— StringToDataSizeConverter 和 NumberToDataSizeConverter 都标着 @since 7.1 ,并在DefaultConversionService ⾥默认注册。Framework 那份实现很简单: DataSize.parse(source) ,不认任何单位注解。
⽽ Boot ⾥早就有⼀份同名类,它是个 GenericConverter ,会去读⽬标字段上的 @DataSizeUnit 注解来决定默认单位。
两个同名类,同⼀个 (String, DataSize) 对,都被注册进同⼀个 ApplicationConversionService 。谁赢?看注册顺序:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java:224
public static void configure(FormatterRegistry registry) {
DefaultConversionService.addDefaultConverters(registry); //① Framework的先进
DefaultFormattingConversionService.addDefaultFormatters(registry); //②
addApplicationFormatters(registry); //③
addApplicationConverters(registry); //④ Boot的后进
}
Framework 的先注册,Boot 的后注册——头插,Boot 的压在上⾯,Boot 赢。于是 @DataSizeUnit(DataUnit.MEGABYTES) private DataSize size; 在 Boot 4 下照常⼯作,Framework 的下沉没有踩到任何⼈的脚。
"后注册者优先"这条规则的价值,就活在这个例⼦⾥:下层往公共层沉淀能⼒时,不必担⼼把上层的增强版本挤掉。
再看⼏条必须记住的默认值:
⚠ canConvert 会撒谎。 官⽅ javadoc 原话:
// [framework] spring-core/src/main/java/org/springframework/core/convert/ConversionService.java:35
* <p>Special note on collections, arrays, and maps types:
* For conversion between collection, array, and map types, this method will return {@code true}
* even though a convert invocation may still generate a {@link ConversionException} if the- underlying elements are not convertible.
集合、数组、Map 之间的转换, canConvert ⼀律返回 true ,元素转不动是 convert 时才炸的事。别拿它当前置校验⽤。
⚠ 转换器返回 null ⽽⽬标是基本类型 → 抛异常,不是给 0。
// [framework] spring-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java:299
private void assertNotPrimitiveTargetType(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.isPrimitive()) {
throw new ConversionFailedException(sourceType, targetType, null,
new IllegalArgumentException("A null value cannot be assigned to a primitive type"));
}
}
⽽ null → Optional 这⼀条是特批的:得到 Optional.empty() 。⚠ 有⼀条暗河,会悄悄接管你的类型。 ObjectToObjectConverter 注册的 pair 是 new ConvertiblePair(Object.class, Object.class) ——⼏乎匹配⼀切,只靠
matches 收敛。它按约定找四样东⻄:源上的 to[Target]() ⽅法、⽬标上的静态 valueOf / of / from 、⽬标上接受单个源类型的构造器。
后果:任何⼀个恰好有 valueOf(String) 或 Xxx(String) 构造器的类,都会被这条约定悄悄接管,哪怕你根本不想要那个语义。要压制它,只能注册⼀个更具体的(String, Xxx) 转换器——因为具体 pair 永远排在 globalConverters 前⾯。
⚠ 还有⼀条改不掉的默认: StringToCollectionConverter 硬编码逗号分隔 + 逐段 trim() ( commaDelimitedListToStringArray ,然后 field.trim() )。想换分隔符?纯 Framework 下没有开关,得换 Boot 那套 @Delimiter 。
九、Formatter:给转换加上 Locale 和注解Formatter 体系不在 spring-core ,在 spring-context 。这条模块边界很多⼈没注意过,但它的理由⼲净利落: core.convert 不认识 Locale , format 才认识——⽽ Locale 要靠 LocaleContextHolder ,那东⻄在 spring-context ⾥, spring-core 不能反向依赖。
Formatter<T> 就是 Printer<T> ( T → String ,认 Locale)加 Parser<T> ( String → T ,认 Locale)。它怎么接进转换体系?折成两个转换器:
// [framework] spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java:88
public void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter) {
addConverter(new PrinterConverter(fieldType, formatter, this));
addConverter(new ParserConverter(fieldType, formatter, this));
}
⼀个 Formatter<T> = ⼀个 T → String + ⼀个 String → T 。 FormattingConversionService 本身继承 GenericConversionService 并实现 FormatterRegistry——同⼀个对象既是转换服务⼜是格式化注册表。
🦴 ⻣灰级细节:打印看源,解析看⽬标。
注解驱动的那两个内部转换器, matches 的判断⽅向是反的: AnnotationPrinterConverter 查 sourceType.hasAnnotation(...) , AnnotationParserConverter 查
targetType.hasAnnotation(...) 。想通了就很⾃然:打印时,注解在你要打印的那个字段上(源);解析时,注解在你要填进去的那个字段上(⽬标)。同⼀个 @DateTimeFormat ,两个⽅向照镜⼦——这就是⼀个注解能同时管住双向的原因。
⚠ 暗礁七:空值处理两个⽅向不对称。
Printer 侧: null 打印成 "" 空串( FormattingConversionService.java:172 )
Parser 侧:空⽩字符串解析成 null ( :210 的 !StringUtils.hasText(text) )于是⼀个 int 字段绑定空串,⾛ Parser 得到 null ,再撞上第⼋节的 assertNotPrimitiveTargetType —— ConversionFailedException 。⽽写回去时 null ⼜变成"" 。⼀个来回,值就不是原来那个了。
⼗、对质:⽼⽂书与新衙⻔,到底谁说了算两套体系并存了⼗六年。真正的裁判只有⼀个⽅法:
// [framework] spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java:117// Custom editor for this type?
PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);
ConversionFailedException conversionAttemptEx = null;// No custom editor but custom ConversionService specified?
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
try {
return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
catch (ConversionFailedException ex) {// fallback to default conversion logic below
conversionAttemptEx = ex;
}
}
}// ...
if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {// ...
if (editor == null) {
editor = findDefaultEditor(requiredType);
}
convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
}判决书(逐⾏核实过):
① findCustomEditor(requiredType, propertyName) ← ⾃定义编辑器(含按属性路径注册的),赢在最前↓ 没有② ConversionService.canConvert → convert ← 有就⾛这⾥,直接 return↓ 没有 / canConvert 为 false / 抛 ConversionFailedException③ findDefaultEditor(requiredType) ← 默认编辑器(含被"覆盖"的那些)
↓ 编辑器没能产出⽬标类型④ ⼀堆标准规则(数组/集合/Map 逐元素、String 构造器、enum、Number 收窄)
↓ 仍不匹配⑤ 若②曾失败 → 抛出②的原始异常;否则再给 ConversionService 最后⼀次机会结论:⾃定义 PropertyEditor 的优先级⾼于 ConversionService 。 ⽼⽂书不但没退休,在"⾃定义"这⼀档上还压着新衙⻔。
理由是它有⼀样新衙⻔⾄今没有的本事:按属性路径注册。 findCustomEditor(type, propertyName) 能针对 order.items[0].price 这样⼀个具体路径挂⼀个编辑器;
ConversionService 只认 (sourceType, targetType) ,做不到这么细。Spring MVC 的 @InitBinder ⽣态整个建在这上⾯。🦴 ⻣灰级细节: Resource 的编辑器故意被塞在第 ③ 档。
ApplicationContext 启动时会挂⼀个 registrar:
// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:734
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));(顺带⼀条本基线变化: ResourceEditorRegistrar 的包从 context.support 移到了 beans.support —— [framework] spring-beans/src/main/java/org/springframework/beans/support/ResourceEditorRegistrar.java:17 。你在⽹上搜到的 6.x 教程⾥那个org.springframework.context.support.ResourceEditorRegistrar ,在本基线上已经不在那⼉了。)
关键在它注册的⽅式:它没有调 registerCustomEditor ,⽽是调了 overrideDefaultEditor ——写进的是"默认编辑器覆盖表",⽽不是"⾃定义编辑器表"。
这⼀步的分量极⼤:因为 findCustomEditor 查的是另⼀张表。于是 String → Resource 这条转换落在了第 ③ 档,排在 ConversionService 后⾯。也就是说,如果容器⾥配了⼀个能把 String 转成 Resource 的 ConversionService ,新衙⻔先赢。
这是刻意的让位:让⽼体系占着位⼦⼲活,但不许它把⻔堵死。
⾄于两套体系的关系,还有⼀个不对称值得记:
新衙⻔能收编旧⽂书,旧⽂书收编不了新衙⻔。 ConvertingPropertyEditorAdapter 把 Converter 包成 PropertyEditor , FormatterPropertyEditorAdapter 把Formatter 包成 PropertyEditor ——反⽅向没有官⽅适配器。原因就是第七节那条罪状: PropertyEditor 有状态,⽽ ConversionService 必须是⽆状态可共享的。有状态的东⻄,包不成⽆状态的。
⚠ 暗礁⼋,也是开场问题⼆的答案:
// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:954// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}⽽ CONVERSION_SERVICE_BEAN_NAME 是个写死的字符串常量: "conversionService" ( [framework] spring-context/src/main/java/org/springframework/context/ConfigurableApplicationContext.java:73 )。
纯 Framework 容器默认没有 ConversionService 。 你必须注册⼀个 bean,⽽且名字必须⼀字不差地等于 conversionService 。名字写成 myConversionService ?容器⼀声不吭地当它不存在,你的所有绑定回落到 PropertyEditor 那条⽼路——不报错、不警告、只是⾏为不⼀样。
这就是"约定优于配置"的账单:约定省下了配置,但约定⼀旦写错,没有任何东⻄会告诉你。
⼗⼀、Boot 叠上来的那⼀层,和它掰断的那两根⻣头Boot 在这两道⻔上都加了东⻄,其中两处是默认值上的正⾯分歧,必须单独记。
分歧⼀:裸路径的归属,两家的答案是相反的。
// [boot] core/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java:44
- When not delegating to an existing resource loader, plain paths without a qualifier
- will resolve to file system resources. This is different from
* {@code DefaultResourceLoader}, which resolves unqualified paths to classpath resources.Boot ⾃⼰在类 javadoc ⾥把这条差异写在了明⾯上。Framework:不带前缀的裸路径 = classpath 资源。Boot:= ⽂件系统资源。 spring.config.location=myconfig/ 这类配置的解析结果,全靠这⼀条。
分歧⼆: spring.config.location 的通配,不是 Ant 通配。
这是本章最容易踩的坑之⼀:同⼀个 Boot 应⽤⾥,同时跑着两套完全不同的通配规矩。
@PropertySource("classpath*:**/x.properties") ⾛的是第六节那套 Ant 匹配。⽽ spring.config.location ⾛的是另⼀个类,规矩是⼿写的、极严的三条Assert.state :
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/LocationResourceLoader.java:127
Assert.state(isPattern(location), () -> String.format("Location '%s' must be a pattern", location));
Assert.state(!location.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX),
() -> String.format("Location '%s' cannot use classpath wildcards", location));
Assert.state(StringUtils.countOccurrencesOf(location, "*") == 1,
() -> String.format("Location '%s' cannot contain multiple wildcards", location));// ...
Assert.state(directoryPath.endsWith("*/"), () -> String.format("Location '%s' must end with '*/'", location));不能⽤ classpath*: 、只能有⼀个 * 、 * 后⾯必须紧跟 / 。 违反任何⼀条直接抛。⽽且它判断"是不是通配"的⽅式极其朴素: location.contains("*") ——⼀个字符串包含判断,跟 AntPathMatcher 毫⽆关系。
同⼀座衙⻔⾥挂着两本通配规矩,只有翻到源码才知道⾃⼰在⽤哪⼀本。 这正是⽂⻛圣经⾥点过的那条批评:"⼀个⾏为常要跨注解、⾃动配置、属性⽂件好⼏处才拼得出来"——这⾥连"拼"都拼不出来,只能读源码。
再说两处 Boot 的加法:
base64: 伪协议。 Boot 通过 spring.factories 把 ProtocolResolver SPI 化了(Framework ⾥这东⻄得⼿动 addProtocolResolver ),挂上去的是:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/io/Base64ProtocolResolver.java:33
class Base64ProtocolResolver implements ProtocolResolver {
private static final String BASE64_PREFIX = "base64:";@Override
public @Nullable Resource resolve(String location, ResourceLoader resourceLoader) {
if (location.startsWith(BASE64_PREFIX)) {
String value = location.substring(BASE64_PREFIX.length());
return new ByteArrayResource(decode(value));
}
return null;
}于是证书、密钥可以直接内联进配置⽂件,不落盘。注意它插在第五节那五岔路的第 ①—— ProtocolResolver 跑在所有标准规则之前,javadoc 明说它"may therefore alsooverride any default rules",连 classpath: 都能劫持。
默认装配。 ⽽ Boot 把开场问题⼆的答案彻底改了:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:217
private boolean addConversionService = true;默认 true ,于是 ApplicationConversionService 同时被装到 Environment ( :499 )和 BeanFactory ( :604 )上。Boot ⾥默认就有,Framework ⾥默认没有。 ⼀条布尔字段的默认值,解释了⼤量"换个环境就不认识这个类型了"的现场。
最后是 Boot 对抽象的⼀次务实的破坏,值得点名。 FilePathResolver 这个 SPI ⼲的事是:某些场景(⽐如 SSL bundle ⾥的证书)必须要⼀个真的 File ,⽽ClassPathResource 在 jar ⾥根本给不出 File 。于是 Boot 加了⼀层,把"没写前缀、被当成 classpath 解析出来"的 location 硬拗回⽂件系统路径。
这是承认抽象漏了。 Resource 的整个卖点就是"你不⽤管它到底在哪",⽽这⾥ Boot 说:对不起,有些活⼉就是得知道它在哪。 与其让上层各写各的绕法,不如在框架⾥开⼀个正式的⼝⼦。不优雅,但诚实。
🎯 三句带⾛1. classpath*: 的全部能⼒来⾃ ClassLoader.getResources(name) 这⼀个只认精确名字的 JDK API;通配是 Spring ⾃⼰⽤ jar 遍历、 Files.walk 、模块内省拼出来的,官⽅ javadoc ⾃⼰写着 "without portability guarantees",两条 WARNING 分别是: classpath*:*.xml 扫不到 jar 根, classpath: + Ant 通配只扫第⼀份。
- 属性绑定的优先级是:⾃定义 PropertyEditor → ConversionService → 默认 PropertyEditor → 标准规则;纯 Framework 容器默认没有ConversionService ,必须注册⼀个名字精确等于 "conversionService" 的 bean,⽽ Boot 默认帮你装上 ApplicationConversionService 。
3. 同⼀个 (S, T) 上后注册的转换器优先( ConvertersForPair.add ⽤ addFirst 头插); Resource 是描述符不是内容, new ClassPathResource(...) 永不失败,只有 exists() 说了算。
承上启下两道⻔看完了。外⻔把字符串变成可读的字节,内⻔把字节⾥的⽂本变成强类型的值——到这⾥,"料"总算⻬了:图纸读进来了,配置值变成了对象,器可以开造。
但有⼀件事⼀直没说破。
这⼀整章⾥,所有动作都是你去问、它来答:你要⼀个资源,它给你⼀个句柄;你要⼀个 int ,它给你⼀个 int 。全是拉。
⽽⼀座真正运转起来的坊,光靠拉是不够的。总装房完⼯了,得让⼈知道;⼀件器造好了、坏了、被换了,关⼼的⼈得收到⻛声;坊要关张了,得让所有还开着的窗⼝⾃⼰收摊。
这些事没法靠"谁想知道谁来问"——问的⼈不知道什么时候该问。
于是坊⾥⽴了⼀⾯锣。敲⼀下,该听⻅的都听⻅。
下⼀章讲事件机制: ApplicationEvent 与 ApplicationListener 、 ApplicationEventMulticaster 到底把锣声传给了谁、 @EventListener 那个注解是怎么在启动时被翻译成监听器的。
以及⼀条必须回源核实、也必须记牢的默认值——这⾯锣,默认是当场敲、当场听,同⼀根线程上⼀路⾛到底的。 不是异步。谁听得慢,谁就把敲锣的⼈⼀起卡住。