Reading a List from properties file and load with spring annotation @Value
Using Spring EL:
@Value("#{'${my.list.of.strings}'.split(',')}")
private List<String> myList;
Assuming your properties file is loaded correctly with the following:
my.list.of.strings=ABC,CDE,EFG
Reading a Map from properties file and load with spring annotation @Value
application.properties:
property.map={first:value, second:value}
then in Java code you can:
@Value("#{${property.map}}")
Map<String, String> map;
Spring @Value annotation with List and default value
@Value("${myapp.values:}#{T(java.util.Collections).emptyList()}")
private List<String> defaultToEmpty;
or
@Value("#{T(java.util.Arrays).asList('${myapp.values:}')}")
private List<String> defaultToEmpty = new ArrayList();
Springboot can't read values from properties file
Considering that you use the prefix = "product-service"
you should declare your class fields as following.
private double first;
private double second;
private double third;
You should also update getters and setters.
You also have another error in your code as well
private List<ProductDTO> productList = Arrays.asList(
new ProductDTO(1,"Tomb Raider",first),
new ProductDTO(2,"10000 rp to lol",second),
new ProductDTO(3,"2k valorant points",third)
);
This field is initialized when your class is initialized. But Spring initializes your bean with a proxy. So when the class is initialized your productList
will have 0
values for first
, second
,third
.
If you wish this to work you should replace
public List<ProductDTO> findAllProducts() {
return productList;
}
with
public List<ProductDTO> findAllProducts() {
return Arrays.asList(
new ProductDTO(1,"Tomb Raider",first),
new ProductDTO(2,"10000 rp to lol",second),
new ProductDTO(3,"2k valorant points",third)
);
}
How to inject List of String arrays in spring from properties file?
Yes, By using Spring Expression Language it can be achieved.
Code:
package com.test.listofarray;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
@SpringBootApplication
@Slf4j
public class TestApplication implements CommandLineRunner {
@Value("#{'${LIST_OF_NESTED_ARRAYS}'.split(';')}")
private List<String[]> list;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
list.forEach(array -> log.info("array ----> {}", Arrays.toString(array)));
}
}
application.properties
LIST_OF_NESTED_ARRAYS=India,USA,Brazil;Asia,Africa
use semi-column(;)
to separate the values of each array in the above property
and give the same semi-column(;)
in the split
function inside @value
annotation.
Verify the output of the injected list in the below output log.
Output:
2021-11-01 17:48:39.105 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : No active profile set, falling back to default profiles: default
2021-11-01 17:48:42.184 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-11-01 17:48:42.206 INFO 11352 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-11-01 17:48:42.207 INFO 11352 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-11-01 17:48:42.411 INFO 11352 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-11-01 17:48:42.411 INFO 11352 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3235 ms
2021-11-01 17:48:45.139 INFO 11352 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
2021-11-01 17:48:45.256 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-11-01 17:48:45.285 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : Started RetryApplication in 6.946 seconds (JVM running for 7.648)
2021-11-01 17:48:45.397 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [India, USA, Brazil]
2021-11-01 17:48:45.400 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [Asia, Africa]
2021-11-01 17:49:03.860 INFO 11352 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-11-01 17:49:03.861 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-11-01 17:49:03.862 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Java : How to load content of .properties file into Properties using spring annotation?
Register your properties file as follows
XML Config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:property-placeholder location="classpath:foo.properties" />
</beans>
Java Config
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
//...
}
Using your properties as follows
@Value( "${jdbc.url}" )
private String jdbcUrl;
You can find a complete working solution in my GitHub repository
https://github.com/mirmdasif/springmvc/tree/master/springproperties
How do I load a list of numbers from a spring properties file
Try adding this bean to your configuration:
@Bean
public ConversionService conversionService() {
return new DefaultConversionService();
}
It will add support to convert String to Collection:
Note that DefaultConversionService registers converters automatically which are appropriate for most environments. This includes collection converters, scalar converters, and also basic Object to String converters. The same converters can be registered with any ConverterRegistry using the static addDefaultConverters method on the DefaultConversionService class.
Reference: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html
How to access a value defined in the application.properties file in Spring Boot
You can use the @Value
annotation and access the property in whichever Spring bean you're using
@Value("${userBucket.path}")
private String userBucketPath;
The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.
Related Topics
How to Get the Current Date/Time in Java
How to Count the Number of Occurrences of an Element in a List
How to Deploy a Javafx 11 Desktop Application with a Jre
How to Decrypt File in Java Encrypted with Openssl Command Using Aes
Why Does the Tostring Method in Java Not Seem to Work for an Array
Concurrent Modification Exception
How to Implement the Java Comparable Interface
Split String into Array of Character Strings
What Is the Point of "Final Class" in Java
How to Override Class Variables in Java
File Upload Along with Other Object in Jersey Restful Web Service
Java Comparison with == of Two Strings Is False
Why Does a Java Method Reference with Return Type Match the Consumer Interface