@RestController
public class ConfigPropertiesController {
@Value("${user.name}")
private String name;
@Value("${user.age}")
private Integer age;
@Value("${user.sex}")
private String sex;
@GetMapping("/user")
public String getUser() {
return "{name:" + name + ",age:" + age + ",sex:" + sex + "}";
}
}
JavaBean
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能
*/
@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map maps;
private List
Controller层
@RestController
public class PersonController {
@Autowired
private Person person;
@GetMapping("/person")
public Person getPerson() {
return person;
}
}
@Component
@ConfigurationProperties(prefix = "person")
//如果只有一个主配置类文件,@PropertySource可以不写
@PropertySource("classpath:person.properties")
@Data
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map map1;
private Map map2;
private List
测试同方式二
方式四: 使用工具类 无需注入获取.yml中的值
新建 BeanConfiguration 类,用于项目启动构造我们的工具类
@Configuration
@Slf4j
public class BeanConfiguration {
@Bean
public YamlConfigurerUtil ymlConfigurerUtil() {
//1:加载配置文件
Resource app = new ClassPathResource("application.yml");
Resource appDev = new ClassPathResource("application-dev.yml");
Resource appProd = new ClassPathResource("application-prod.yml");
YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
// 2:将加载的配置文件交给 YamlPropertiesFactoryBean
yamlPropertiesFactoryBean.setResources(app);
// 3:将yml转换成 key:val
Properties properties = yamlPropertiesFactoryBean.getObject();
String active = null;
if (properties != null) {
active = properties.getProperty("spring.profiles.active");
}
if (StringUtils.isEmpty(active)) {
log.error("未找到spring.profiles.active配置!");
} else {
//判断当前配置是什么环境
if ("dev".equals(active)) {
yamlPropertiesFactoryBean.setResources(app, appDev);
} else if ("prod".equals(active)) {
yamlPropertiesFactoryBean.setResources(app, appProd);
}
}
// 4: 将Properties 通过构造方法交给我们写的工具类
return new YamlConfigurerUtil(yamlPropertiesFactoryBean.getObject());
}
}
工具类实现
public class YamlConfigurerUtil {
private static Properties ymlProperties = new Properties();
public YamlConfigurerUtil(Properties properties) {
ymlProperties = properties;
}
public static String getStrYmlVal(String key) {
return ymlProperties.getProperty(key);
}
public static Integer getIntegerYmlVal(String key) {
return Integer.valueOf(ymlProperties.getProperty(key));
}
}
调用示例
@RestController
public class PersonController {
@GetMapping("/msg")
public String getMessage() {
return YamlConfigurerUtil.getStrYmlVal("person.lastName");
}
}