⽬录
如何获取yml⾥⾯的属性值
开发环境项⽬结构pom依赖springboot启动类person.ymlperson.javaDog.javaSpringbootDemoApplicationTests控制台输出
获取.yml中⾃定义参数
通过@Value获取
通过@ConfigurationProperties(prefix = \"weixinAndAli\")注解
如何获取yml⾥⾯的属性值
开发环境
ideajdk1.8
项⽬结构
pom依赖
springboot启动类
package com.springboot.springboot_demo;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;import org.springframework.core.io.ClassPathResource;
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args); } /**
* 设置⾃定义yml位置 *
* @return */
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); yaml.setResources(
new ClassPathResource[] { /** 请求url地址 */
new ClassPathResource(\"config/person.yml\") });
pspc.setProperties(yaml.getObject()); return pspc; }}
person.yml
person:
lastName: zhangsan age: 18 boss: false
birth: 2017/12/12
maps: {k1: v1,k2: v2} lists: - lisi - zhaoliu
dog:
name: ⼩狗 age: 2
person.java
package com.springboot.springboot_demo.pojo; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component; import java.util.Date;import java.util.List;import java.util.Map; /**
* 将配置⽂件中配置的每⼀个属性的值映射到person
* @ConfigurationProperties 告诉springboot 将本类中的值与配置⽂件中的值绑定 * prefix = \"person\" 配置⽂件下的那个属性下的
* 只有这个组件是容器中的组件才能使⽤@Component */
@Data
@Component
@ConfigurationProperties(prefix = \"person\")public class Person {
private String lastName; private Integer age; private Boolean boss; private Date birth;
private Map