Подтвердить что ты не робот

Как загрузить ресурс и использовать его содержимое в виде строки в Spring

Как загрузить содержимое ресурса Spring и использовать его для установки свойства bean или передать его как конструктор аргументов?

Ресурс содержит свободный текст.

4b9b3361

Ответ 1

<bean id="contents" class="org.apache.commons.io.IOUtils" factory-method="toString">
    <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>

Это решение требует Apache Commons IO.

Другое решение, предложенное @Parvez, без зависимостей IO от Apache Commons -

<bean id="contents" class="java.lang.String">
    <constructor-arg>
        <bean class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
            <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
        </bean>     
    </constructor-arg>
</bean>

Ответ 2

Просто прочитайте:

    try {
        Resource resource = new ClassPathResource(fileLocationInClasspath);
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()),1024);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line).append('\n');
        }
        br.close();
        return stringBuilder.toString();
    } catch (Exception e) {
        LOGGER.error(e);
    }

Ответ 3

Это один из способов сделать это без использования какой-либо внешней библиотеки.. по умолчанию предоставляется spring.. файл environment.properties содержит пары значений ключа... ссылайтесь на каждое значение с помощью ${key}

здесь, в моем примере, я поддерживаю реквизиты базы данных

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list value-type="org.springframework.core.io.Resource">
            <value>classpath:environment.properties</value>

        </list>
    </property>
</bean>
<bean id="mySQLdataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${JDBC.driver}" />
    <property name="url" value="${JDBC.URL}" />
    <property name="username" value="${JDBC.username}" />
    <property name="password" value="${JDBC.password}" />
</bean>

Ответ 4

daoway ответ был очень полезен, и после Adrian я добавляю конфигурацию фрагмент, похожий на код daoway

<bean id="contents" class="org.springframework.core.io.ClassPathResource">
    <constructor-arg value="path/to/resource.txt"/>
</bean>

Из вашего компонента

    @Autowired
    private Resource contents;

    @PostConstruct
    public void load(){
        try {
            final InputStream inputStream = contents.getInputStream();
                //use the stream 
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream ,1024);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            br.close();
     }catch (IOException e) {
            LOGGER.error(message);
     }
  }

Ответ 5

В одной строке попробуйте это прочитать test.xml:

String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset()  );