Spring Boot reads properties configuration files.
In Spring Boot, you can use the @ConfigurationProperties annotation to read properties configuration files.
Firstly, you need to add the following dependencies in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Then, in the configuration class, use the @ConfigurationProperties annotation and specify the prefix of the properties file, as shown below:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String name;
private String age;
// getter and setter methods
}
In the configuration file, use “myconfig” as a prefix to define properties, as shown below:
myconfig.name=John
myconfig.age=25
Finally, in other classes you can inject the configuration class using the @Autowired annotation and make use of its properties, as shown below:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
private MyConfig myConfig;
public void printConfig() {
System.out.println("Name: " + myConfig.getName());
System.out.println("Age: " + myConfig.getAge());
}
}
In this way, the property values in the configuration file will be automatically injected into the MyConfig class and can be used in other classes.