Professional Documents
Culture Documents
=> if we use @Value, we can read only one value at a time into our class.
=> This time we are using Spring boot concept that loads multiple keys at a time
into our code.
Note:
a. Prefix given in properties file and @ConfigurationProperties("") must be
matching, else values are not taken into application.
Variables holds default values.
c. @Value uses Reflection based data read. So, no set/get method required.
----application.properties---
my.app.id=10
my.app.code=NIT
my.app.version=3.3
------------------------------
Runner class:
package in.nareshit.raghu;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("my.app")
public class MyConfigDataReader implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(this);
}
a. List/Set/Array
For this concept we should use index (starts from zero) with below format
prefix.variable[index]=value
Ex: my.app.info[0]=SAMPLE
b. Map/Properties
For this concept we should use key=val format
prefix.variable.key=value
ex: my.app.data.G1=ACTIVE
=======================Code=====================================
---application.properties---
my.app.id=10
my.app.code=NIT
my.app.version=3.3
my.app.info[0]=A
my.app.info[1]=B
my.app.info[2]=C
my.app.data.G1=ACTIVE
my.app.data.G2=NONE
my.app.dob.dtlId=101
my.app.dob.dtlCode=ABC
-------------------------
2. Model class
package in.nareshit.raghu;
@Override
public String toString() {
return "Details [dtlId=" + dtlId + ", dtlCode=" + dtlCode + "]";
}
3. Runner class
package in.nareshit.raghu;
//ctrl+shift+O
import java.util.Arrays;
import java.util.Properties;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("my.app")
public class MyConfigDataReader implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(this);
}