Springboot如何从yml或properties配置文件中获取属性值

配置文件如下:

server.port=8081
person.name=孙超
person.age=22
person.birth=2022/12/12
person.map.k1=k1
person.list=a,bc,c
person.dog.name=xiaogou
person.dog.age=2

Springboot如何从yml或properties配置文件中获取属性值

@Value 获取配置文件的值

package com.sunchao.demo.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sunyc
 * @create 2022-04-24 9:43
 */
//将配置文件中的值映射到person中
//@ConfigurationProperties 告诉springboot将本类中的所有属性与配置文件中相关的属性配置
//这个组件是容器中的组件,才能提供功能加@Component注解
@Component
//@ConfigurationProperties(prefix = "person")
@Validated//数据校验
public class Person {
//@Email
@Value("${person.name}")//从properties配置文件中获取值
String name;
@Value("${person.age}") //从properties配置文件中获取值
int age;
@Value("${person.birth}")//从properties配置文件中获取值
Date birth;
Map<String,Object> map;
Dog dog;
List list;

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
", map=" + map +
", dog=" + dog +
", list=" + list +
'}';
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Date getBirth() {
return birth;
}

public void setBirth(Date birth) {
this.birth = birth;
}

public Map<String, Object> getMap() {
return map;
}

public void setMap(Map<String, Object> map) {
this.map = map;
}

public Dog getDog() {
return dog;
}

public void setDog(Dog dog) {
this.dog = dog;
}

public List getList() {
return list;
}

public void setList(List list) {
this.list = list;
}
}

4、@PropertySource&@ImportResource&@Bean

@PropertySource:加载指定的配置文件;

Springboot如何从yml或properties配置文件中获取属性值

Springboot如何从yml或properties配置文件中获取属性值

 使用配置类的方式给IOC容器中添加组件,不用xml的配合方式

Springboot如何从yml或properties配置文件中获取属性值

Springboot如何从yml或properties配置文件中获取属性值