yml文件
charm:
name: "大黄"
age: 18
有两种方式 一种 @ConfigurationProperties 另一种是@value ,这里展示前者
package com.example.bryangp.web.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "charm")
public class Charm {
private String name;
private int age;
}
测试
package com.example.bryangp;
import com.example.bryangp.web.entity.Charm;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BryangpApplicationTests {
@Autowired
Charm charm;
@Test
void contextLoads() {
System.out.println(charm.toString());
}
}
打印

本文介绍如何使用YML文件配置Spring Boot应用程序,并通过@ConfigurationProperties注解将配置属性绑定到Java对象中。示例代码展示了如何创建实体类接收配置信息及简单的单元测试。
1108

被折叠的 条评论
为什么被折叠?



