gpt4 book ai didi

java - 如何使用 java 中的注释从类路径加载甚至 Autowiring .json 文件?

转载 作者:行者123 更新时间:2023-12-01 06:15:26 24 4
gpt4 key购买 nike

如何使用 java 中的 spring 注释从类路径加载甚至 Autowiring .json 文件?

//Something like this in my controller in STS:
@value("file:/resources/json/myJsonfile.json")
Resource jsonTemplateFile;

最佳答案

创建一个抽象类:

    public abstract class ResourceLoadingTest {

@Rule public TestName testName = new TestName();

protected String loadResource(String fileName) throws IOException {
final URL resource = getClass().getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("No resource file named <" + fileName + "> could be loaded from the classpath.");
}

return Resources.toString(resource, Charsets.UTF_8);
}

/**
* Loads a JSON resource whose name is derived from the currently running
* test. The derived reosurce name is "[test-method-name].json".
* For example, if this method is called from a test method named
* <code>testSomeBehavior</code>, then the resource name to be loaded will
* be <code>testSomeBehavior.json</code>
*/
protected String loadCurrentTestJSON() throws IOException {
return loadResource(testName.getMethodName() + ".json");
}

/**
* Loads a XML resource whose name is derived from the currently running
* test. The derived reosurce name is "[test-method-name].xml".
* For example, if this method is called from a test method named
* <code>testSomeBehavior</code>, then the resource name to be loaded will
* be <code>testSomeBehavior.xml</code>
*/
protected String loadCurrentTestXML() throws IOException {
return loadResource(testName.getMethodName() + ".xml");
}
}

然后在子类中:

    public static void main(String[] args){
loadSetupMessage("myJsonfile.json");
}

protected void loadSetupMessage(String fileName) throws IOException {
String rawMessage = this.loadResource(fileName);
System.out.println(String.format("loaded class %s", rawMessage);
}

并将 myJsonfile.json 放置在同一包层次结构中。

关于java - 如何使用 java 中的注释从类路径加载甚至 Autowiring .json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com