A convenient way compared to @Value
Example 1:
@SpringBootApplication
@EnableConfigurationProperties(ConfigProperties.class)
public class Demo12Application {
public static void main(String[] args) {
SpringApplication.run(Demo12Application.class, args);
}
}
@Data
@Component
@PropertySource("classpath:foo.properties")
@ConfigurationProperties
class ConfigProperties {
private String priority;
private List<String> listOfValues;
}
@RestController
class ConfigController {
@Autowired
ConfigProperties configProperties;
@GetMapping("/ok")
public String ok() {
return configProperties.toString();
}
}
Example 2: add prefix for each value
@SpringBootApplication
@EnableConfigurationProperties(ConfigProperties.class)
public class Demo12Application {
public static void main(String[] args) {
SpringApplication.run(Demo12Application.class, args);
}
}
// We use @Configuration so that Spring creates a Spring bean in the application context.
@Configuration
@ConfigurationProperties(prefix = "mail")
@Data
class ConfigProperties {
private String hostName;
private int port;
private String from;
}
@RestController
class ConfigController {
@Autowired
ConfigProperties configProperties;
@GetMapping("/ok")
public String ok() {
return configProperties.toString();
}
}
Example 3: add validation
@SpringBootApplication
@EnableConfigurationProperties(ConfigProperties.class)
public class Demo12Application {
public static void main(String[] args) {
SpringApplication.run(Demo12Application.class, args);
}
}
@Data
@Component
@PropertySource("classpath:foo.properties")
@ConfigurationProperties
@Validated
class ConfigProperties {
@Max(5)
@Min(0)
private int threadPool;
@NotEmpty
private String email;
}
@RestController
class ConfigController {
@Autowired
ConfigProperties configProperties;
@GetMapping("/ok")
public String ok() {
return configProperties.toString();
}
}
foo.properties
threadPool = 10
email = ""
It will have error