智慧·快乐·成长——科技造福于人。

springboot编译任务里有关资源抽取的实现逻辑

资源抽取是指对类似*.properties等属性配置资源文件的提取,springboot团队对springboot源码的资源提取机制做了专门的实现。
springboot编译任务对资源抽取的实现逻辑:

public class ExtractResources extends DefaultTask {
	/** 定义一个占位符助手:前后缀分别为${、} */
	private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");

	private final Map properties = new HashMap<>();

	private final DirectoryProperty destinationDirectory;

	private List resourceNames = new ArrayList<>();

	/**
	 * 默认构造器,初始化目标目录为当前项目名
	 */
	public ExtractResources() {
		this.destinationDirectory = getProject().getObjects().directoryProperty();
	}

	@Input
	public List getResourceNames() {
		return this.resourceNames;
	}

	public void setResourcesNames(List resourceNames) {
		this.resourceNames = resourceNames;
	}

	@OutputDirectory
	public DirectoryProperty getDestinationDirectory() {
		return this.destinationDirectory;
	}

	public void property(String name, String value) {
		this.properties.put(name, value);
	}

	@Input
	public Map getProperties() {
		return this.properties;
	}

	/**
	 * 
	 * @throws IOException
	 */
	@TaskAction
	void extractResources() throws IOException {
		// 遍历资源文件
		for (String resourceName : this.resourceNames) {
			InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourceName);
			if (resourceStream == null) {
				throw new GradleException("Resource '" + resourceName + "' does not exist");
			}
			// 把资源文件的内容读取到字符串中
			String resource = FileCopyUtils.copyToString(new InputStreamReader(resourceStream, StandardCharsets.UTF_8));
			// 按指定的前后缀找到文本内容中的占位符,然后取出占位符中确定的属性key,再从指定的properties里取出对应的value去替换原来的占位符,
			// 最后返回替换后的文本配置
			resource = this.propertyPlaceholderHelper.replacePlaceholders(resource,
					(placeholder) -> this.properties.get(placeholder));
			// 将返回的文本配置重写回到目标目录下的文件中
			FileCopyUtils.copy(resource,
					new FileWriter(this.destinationDirectory.file(resourceName).get().getAsFile()));
		}
	}

}

转载请注明:转自《springboot编译任务里有关资源抽取的实现逻辑
本文地址:https://www.zhiletu.com/archives-10635.html

赞赏

微信赞赏支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!