简体   繁体   English

将XML数据文件春季注入Java类

[英]Spring Injection of XML Data Files to Java Classes

Is there a way to easily use Spring Injection to grab one or more *.xml data files from a folder location (either in a deployed *.war or on a server folder) and inject that data from the *.xml files into a Java class (eg in a web service)? 有没有一种方法可以轻松地使用Spring Injection从文件夹位置(在已部署的* .war或服务器文件夹中)捕获一个或多个* .xml数据文件,并将该数据从* .xml文件注入Java中类(例如在Web服务中)? I have been asked by another programmer if I can do this. 另一个程序员问我是否可以这样做。

I've had a look at a few links on stackoverflow, but so far the easiest way I've found is to put the *.xml files into a particular folder location (eg WEB-INF/classes) and use something like this to retrieve them: 我看过关于stackoverflow的一些链接,但是到目前为止,我发现的最简单的方法是将* .xml文件放入特定的文件夹位置(例如WEB-INF / classes),并使用类似的方法来检索它们:

Thread.currentThread().getContextClassLoader.getResourceAsStream("/WEB-INF/classes/data.xml")

The above method is easy; 上面的方法很简单; however, it is obviously not Spring Injection. 但是,显然不是Spring Injection。 Is there a way to do this using Spring Injection instead? 有没有办法使用Spring Injection来做到这一点? I would have thought that since configuration files can be loaded this way, that xml data could also be loaded similarly. 我本以为,由于可以通过这种方式加载配置文件,因此也可以类似地加载xml数据。

Thanks. 谢谢。

Spring provides a class called Resource which you can use to inject resource files into a spring bean. Spring提供了一个名为Resource的类,您可以使用该类将资源文件注入Spring Bean。 So you can do this: 因此,您可以执行以下操作:

public class Consumer {

    public void setResource(Resource resource) {
        DataInputStream resourceStream = new DataInputStream(resource.getInputStream());
        // ... use the stream as usual
    }

    ...
}

Then: 然后:

<bean class="Consumer">
    <property name="resource" value="classpath:path/to/file.xml"/>
</bean>

or, 要么,

<bean class="Consumer">
    <property name="resource" value="file:path/to/file.xml"/>
</bean>

You can also directly use the @Value annotation: 您也可以直接使用@Value批注:

public class Consumer {

    @Value("classpath:path/to/file.xml")
    private Resource resource;

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM