LoginSignup
1
1

More than 5 years have passed since last update.

springのxml configurationでファイルをstringのプロパティに入れる

Last updated at Posted at 2017-06-23

最近はjava configurationが普通なのであまり困る事はないのだけど。たとえば、spring-batchをxmlで書いていて、sqlのプロパティにファイルへ外出ししたSQLの文字列を設定したい場合を考える。

FileCopyUtils

java - How do I load a resource and use its contents as a string in Spring - Stack Overflow に書いてあるやり方。

    <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>

ファイルから読み込んでstring返すクラスを作る

上はXMLですべて完結するのだがちょっと長ったらしい。なので、それをするだけのbeanを自前で作ることを考える。

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 追記 前は下のように書いてたけど環境によってはFileNotFoundExceptionになる。
                //詳細は別途書く。かも。
                //File file = ResourceUtils.getFile(location);
                //return Files.lines(file.toPath(), Charset.defaultCharset()).collect(Collectors.joining(System.lineSeparator()));


    }
}

springのlocationを受け取ってそのファイルの中身をすべて読んで文字列をして返すだけのクラスを作る。

<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>

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1