These days, java configuration is normal, so I don't have much trouble. For example, suppose you are writing spring-batch in xml and want to set the sql property to the SQL string that went out to the file.
FileCopyUtils [java --How do I load a resource and use its contents as a string in Spring --Stack Overflow](https://stackoverflow.com/questions/14022839/how-do-i-load-a-resource-and-use -its-contents-as-a-string-in-spring)
<bean id="sql" class="java.lang.String">
<constructor-arg>
<bean class="org.springframework.util.FileCopyUtils"
factory-method="copyToByteArray">
<constructor-arg value="classpath:a.txt"
type="java.io.InputStream" />
</bean>
</constructor-arg>
</bean>
The above is all completed with XML, but it seems to be a little long. So, think about making your own bean that just does that.
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.stream.Collectors;
import org.springframework.util.ResourceUtils;
public class ResourceToStringUtils {
public String to(String location) throws IOException {
ApplicationContext ctx = ...;
BufferedReader in
= new BufferedReader(new InputStreamReader(resource.getInputStream(), Charset.defaultCharset()));
return = in.lines().collect(Collectors.joining(System.lineSeparator()));
// 2017/0/02 Addendum I used to write as below, but depending on the environment, FileNotFoundException will occur.
//Details will be written separately. maybe.
//File file = ResourceUtils.getFile(location);
//return Files.lines(file.toPath(), Charset.defaultCharset()).collect(Collectors.joining(System.lineSeparator()));
}
}
Create a class that receives the location of spring, reads all the contents of the file, converts it to a string, and returns it.
<bean id="resourceToStringUtils"
class="kagamihoge.hogehoge.ResourceToStringUtils"></bean>
...
<property name="p" value="#{resourceToStringUtils.to('file:hoge.txt')}"></property>
...
<property name="p" value="#{resourceToStringUtils.to('classpath:foo.sql')}"></property>
Recommended Posts