Spring properties配置官网

https://docs.spring.io/spring...

image.png
image.png

通过注解绑定application.yml
单个配对可以通过
@Value(${user.username})
private String username;

@ConfigurationProperties    作用 常用与bean属性和yml配置文件的绑定
prefix    可以指定配置文件某一个节点,该节点中的子节点将自动和属性进行绑定
松散绑定:(USERNAME、userName、user_name、user-name)
以上4中命名是可以自动绑定bean属性
 
  <!-- 会生成META-INF 元数据 用于提供idea自动提示配置文件 -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <!-- 依赖不会传播 -->
      <optional>true</optional>
  </dependency>

@Validated    支持jsr-303数据校验
需要使用还需要添加该依赖
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>

image.png

application.yml文件

user:
  userName: "LLL"

# 集合 list、set
# 写法一
  hobbies:
    - 1
    - 2
    - 3
# 写法二
  hobbies: [1,2,3]

# 集合 map
# 写法一
  girl-friend:
    13 : 陈奕迅
    14 : 张国荣
# 写法二
    girl-friend: {13: 陈奕迅,14: 张国荣}

# 对象
  address:
    id: 1
    desc: 北京

# 拼接 引用值
  address:
    id: 1
    desc: ${userName}北京

# 随机生成
 age: ${random.int}
# ${random.value}    
# ${random.int}
# ${random.long}
# ${random.uuid}
# ${random.int(10)}                几位数
# ${random.int[1024,65536]}        范围1024-65536

文件绑定

@Data
@Component
@ConfigurationProperties(prefix="user")
// 绑定到某个properties 只允许是properties文件  data为文件夹
@PropertySource("classpath:/data/user.properties")
public class User {

    @NotNull
    private String username;

    private Integer age;

    private Date birthday;

    private List<String> hobbies;

    private Map<Integer,String> girlFriend;

    private Address address;
}

LLL_
15 声望3 粉丝