Administrator
发布于 2024-08-18 / 3 阅读
0
0

resource read

问题:如何读取src/main/resources下的配置文件(资源文件)呢?

要解决这个问题,我们先来了解几个背景知识

classpath*classpath

可以通过classpath*前缀指定,从所有的类路径下获取指定的文件,与classpath前缀的区别:

是classpath前缀只能获取当前类路径下的资源文件,

而classpath*前缀可以获取所有类路径下的资源文件,包括jar包中的

String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

PathMatchingResourcePatternResolver

借助PathMatchingResourcePatternResolver,即可实现读取src/main/resources下的配置文件.

这个PathMatchingResourcePatternResolver,是spring提供的,他有一个getResources方法,就是根据classpath*:标识,获取所有类路径下的资源文件,包括jar包中的,如下

// org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources

@Override
	public Resource[] getResources(String locationPattern) throws IOException {
		Assert.notNull(locationPattern, "Location pattern must not be null");
		if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
			// a class path resource (multiple resources for same name possible)
			if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
				// a class path resource pattern
				return findPathMatchingResources(locationPattern);
			}
			else {
				// all class path resources with the given name
				return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
			}
		}
		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);
			if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
				// a file pattern
				return findPathMatchingResources(locationPattern);
			}
			else {
				// a single resource with the given name
				return new Resource[] {getResourceLoader().getResource(locationPattern)};
			}
		}
	}

实际使用

public static Resource getResourceByPath(String path, PathMatchingResourcePatternResolver resourceResolver) throws IOException {
        Resource[] templateResources = resourceResolver.getResources(path);
        if (templateResources == null || templateResources.length != 1) {
            throw new IOException("未找到对应的模版或者模板存在冲突");
        }
        return templateResources[0];
    }
 private static final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

image-20240818070701234


评论