spring boot — day2 configuration
Focus on how to set up config from application.properties/*.properties
Using: @Component, @ConfigurationProperties, @PropertySource
1. get data from application.properties
- add config in application.properties
string1=withoutPrefix
int1=100
add a class for get config from properties
@Component
@ConfigurationProperties()
@Data //use Data with lombok, or your write setter and getter
public class ApplicationConfig {
public String string1;
public int int1;
}
in other class use @Resource
d for spring boot bind data
@RestController
public class ConfigController {
@Resource
ApplicationConfig applicationConfig;
@GetMapping("/config")
public Object test() {
System.out.println(applicationConfig.string1);
System.out.println(applicationConfig.int1);
return "done";
}
}
2. get data from application.properties with prefix
- add config in application.properties
xxx.string1=withoutPrefix
xxx.int1=100
add a class for get config from properties
@Component
@ConfigurationProperties(prefix = "xxx")
@Data
public class ApplicationConfigWithPrefix {
public String string1;
public int int1;
}
in other class also use @Resource
@RestController
public class ConfigController {
@Resource
ApplicationConfigWithPrefix applicationConfigWithPrefix;
@GetMapping("/config")
public Object test() {
System.out.println(applicationConfigWithPrefix.string1);
System.out.println(applicationConfigWithPrefix.int1);
return "done";
}
}
3. get data from other .properties file
add other .properties file , ex :`other.properties` in resource
other.string1=other
other.int1=300
use PropertySource to set which file to get data
@Component
@PropertySource({"classpath:other.properties"})
@ConfigurationProperties(prefix = "other")
@Data
public class OtherConfig {
public String string1;
public int int1;
}@RestController
public class ConfigController {
@Resource
OtherConfig otherConfig;
@GetMapping("/config")
public Object test() {
System.out.println(otherConfig.string1); //other
System.out.println(otherConfig.int1); //300
return "done";
}
}
4 setup data to create Bean
- create data class, ex: user
@Data
public class User {
private String name1;
private String password;
}
- set value in application.properties
user.name1=user123
user.password=password123
- create a configuration class
@Configuration
public class ConfigurationAutoBindData {
@Bean
@ConfigurationProperties(prefix = "user")
public User user() {
return new User();
}
}
using:
@RestController
public class ConfigController {
@Resource
User user;
@GetMapping("/config")
public Object test() {
System.out.println(user.getName1());
System.out.println(user.getPassword());
return "done";
}
}
NOTE:
all config class need provide setter / getter, if only use `public` spring boot will not set data in class
git: https://github.com/cwnga2/spring_boot_study/tree/main/day2_configuration