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

标签 java json spring resources classpath

如何使用 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/

相关文章:

java - 扩展 CrudRepository,从一列中选择全部?

java - Spring 映射处理程序未将我的curl 请求映射到方法

java - 从 C# 到 JAVA 的 3DES 加密

json - Jackson 对象映射器未使用映射器的 setDateFormat 或 setSerializationInclusion

java - 在不破坏 JSON 的情况下转义 JSON 字符串的值

spring - SpEL可以与spring xml配置中的import语句一起使用吗

java - Jacoco 插件不报告重命名的集成测试类的覆盖率

java - 在 Java 中检查空值的最佳方法是什么?

java - 为 Nuxeo 安装启用 Hibernate "show_sql"

c# - 解析值后遇到意外字符 : 6. Path '[0]