简体   繁体   中英

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)? 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:

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

The above method is easy; however, it is obviously not Spring Injection. Is there a way to do this using Spring Injection instead? I would have thought that since configuration files can be loaded this way, that xml data could also be loaded similarly.

Thanks.

Spring provides a class called Resource which you can use to inject resource files into a 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:

public class Consumer {

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

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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