SpringBoot02_配置文件、三种读取配置文件方式(下)

②. 读取配置的三种方式


  • ①. 使用@Value(“${server.port}”)


  • ②. 注入Environment


  • ③. ConfigurationProperties(prefix=``)


  • ④. 代码展示


server:
  port: 8888
mycar:
  branch: "雅阁"
  price: "20w"
name: abc
#1.对象(map)键值对的集合
person:
  name: TANGZHI #${name}
  age: 24
  birthday: 2021/05/24 20:12:33
  address:
    - beijing
    - shanghai
  # List集合
  animal:
    - 猴子
      大象
    - 青蛙
  # Map集合
  score:
    english:
      first: 30
      second: 40
      third: 50
    math:
      100
  # Set集合
  salary:
    - 1000
    - 2000
#行内写法
address2: [beijing2,shanghai2]
#3.纯量
msg1: 'hello \n word' # 这里正常输出
msg2: "hello \n word" # 这里会带上转行符号
#spring:
#  banner:
#    image:
#      location: classpath:bug.png


@Data
@AllArgsConstructor
@NoArgsConstructor
// 第一种方式,使用Component+ConfigurationProperties注解的方式加载yaml文件
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Date birthday;
    private String[]address;
    private List<String> animal;
    private Map<String,Object> score;
    private Set<Double> salary;
}


@Slf4j
@RestController
public class myController {
    /*(1).通过@value注解从配置文件中获取值*/
    @Value("${msg1}")
    private String msg1;
    @Value("${msg2}")
    private String msg2;
    /*2.Environment*/
    @Autowired
    private Environment env;
    @Autowired
    Car car;
    //(3). 通过ConfigurationProperties注解进行绑定
    @Autowired
    Person person;

    @GetMapping("/car")
    public Car getMyCar(){
        log.info("***********");
        log.info("***********");
        return car;
    }
    @GetMapping("/person")
    public Person getPerson(){
        //msg1:hello \n word
        System.out.println("msg1:"+msg1);
        /**
         * msg2:hello
         // word
         */
        System.out.println("msg2:"+msg2);
        String address = env.getProperty("address2[0]");
        //beijing2
        System.out.println(address);
        return person;
    }
}


SpringBoot02_配置文件、三种读取配置文件方式(下)

上一篇:【C++11】lambda 表达式解析


下一篇:Lambda 表达式的示例