SpringBoot项目获取统一前缀配置以及获取非确定名称配置
在SpringBoot项目中,我们经常看到统一前缀的配置,我们该怎么统一获取
my.config.a.name=xiaoming
my.config.a.age=18
my.config.a.address=guangdongmy.config.b.name=xiaomli
my.config.b.age=20
my.config.b.address=shandong
方式一:使用对应的配置类并结合注解:@ConfigurationProperties(prefix = “xxx.xxx”)
配置文件:
my.config.name=xiaoming
my.config.age=18
my.config.address=guangdong
对应的配置类:MyProperties
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** @author gooluke*/
@Component
@ConfigurationProperties(prefix = "my.config")
@Getter
@Setter
public class MyProperties {private String name;private int age;private String address;
}
获取配置类,打印属性:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@Autowiredprivate MyProperties myProperties;@RequestMapping("/show")public void show() {System.out.println("myProperties.getName() = " + myProperties.getName());System.out.println("myProperties.getAge() = " + myProperties.getAge());System.out.println("myProperties.getAddress() = " + myProperties.getAddress());}
}
打印结果:
方式二:获取统一前缀,而后面非确定字段名的配置
配置文件:
my.config.a.name=xiaoming
my.config.a.age=18
my.config.a.address=guangdongmy.config.b.name=xiaomli
my.config.b.age=20
my.config.b.address=shandong
对应的配置类:
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.Map;/*** @author gooluke*/
@Component
@ConfigurationProperties(prefix = "my")
@Getter
@Setter
public class MyProperties2 {//这里的config得对应上my.config.xx里的configprivate Map<String, UserInfoConfig> config;@Setter@Getterpublic static class UserInfoConfig {private String name;private Integer age;private String address;}}
获取配置类,打印属性:
@Autowired
private MyProperties2 myProperties2;@RequestMapping("/show2")
public void show2() {Map<String, MyProperties2.UserInfoConfig> config = myProperties2.getConfig();config.forEach((user, userInfoConfig) -> {System.out.println("user = " + user);System.out.println("userInfoConfig.getName() = " + userInfoConfig.getName());System.out.println("userInfoConfig.getAge() = " + userInfoConfig.getAge());System.out.println("userInfoConfig.getAddress() = " + userInfoConfig.getAddress());});
}
打印结果: