How can I load a Spring resource contents and use it to set a bean property or pass it as an argument constructor?
The resource contains free text.
How can I load a Spring resource contents and use it to set a bean property or pass it as an argument constructor?
The resource contains free text.
In one line try this to read test.xml:
String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset() );
<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>
This solution requires Apache Commons IO.
Another solution, suggested by @Parvez, without Apache Commons IO dependency is
<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>
Just read it :
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);
}
Update in 2021.
You can use Spring's Resource
Interface to get the content of text file, and then use StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
to get the text.
An example as follow:
@Value("classpath:appVersionFilePath")
private Resource resource;
@GetMapping(value = "/hello")
public HttpResult<String> hello() throws IOException {
String appVersion = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
// ...
}
This is one way of doing it without using any external library.. default provided by spring.. environment.properties file contains key value pairs...reference each value with ${key}
here in my example, I am keeping database props
<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>
daoway answer was very helpful, and following Adrian remark I am adding a configuration snippet similar to daoway's code
<bean id="contents" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="path/to/resource.txt"/>
</bean>
From your component
@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);
}
}
Spring
private String readResource(String fileName){
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("resourceSubfolder/"+fileName)
try{
Reader reader = new InputStreamReader(resource.getInputStream());
return FileCopyUtils.copyToString(reader);
} catch (IOException e){
e.printStackTrace();
}
return null;
}