SpringBoot 04——获取数据

该博客详细介绍了在SpringBoot中通过@ConfigurationProperties和@Value注解从YAML配置文件获取数据的方法。示例代码展示了如何创建Person类并注入配置属性,以及在HelloController中使用@Value和@Autowired读取配置信息。内容包括配置文件格式、Bean注入以及属性获取的多种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取配置文件数据的方式

  • @Value
  • Environment
  • ConfigurationProperties

具体代码实例

首先是YAML格式的配置文件

application.yml

person:
  name: zhangsan
address:
  - beijing
  - shanghai
message1: 'hello \n world' # 单引忽略转移字符
message2: "hello \n world" # 双引识别转移字符

创建Person类用作测试,创建相关类主要服务于@ConfigurationProperties注解进行测试内容,注意要给相关属性配置get和set函数,没有set函数无法进行注入,需要注入的属性名字需要与配置文件中的属性名字相同才能够进行自动注入
Person

@Component
@ConfigurationProperties(prefix = "person")//prefix设置注入属性前缀
public class Person {
    private String name;
    private String age;
    private String[] address;
    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    public String[] getAddress() {
        return address;
    }

    public void setAddress(String[] address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", address=" + Arrays.toString(address) +
                '}';
    }
}

HelloController

@RestController
@PropertySource(value = "classpath:application.yml")
public class HelloController {

    @Value("${name}")
    private String name;

    @Value("${person.name}")
    private String name2;

    @Value("${address[0]}")
    private String address;

    @Value("${message1}")
    private String message1;

    @Value("${message2}")
    private String message2;

    @Autowired
    private Environment env;

    @Autowired
    private Person person;

    @RequestMapping("/hello")
    public String hello(){
        System.out.println(name);
        System.out.println(name2);
        System.out.println(address);
        System.out.println(message1);
        System.out.println(message2);
        System.out.println("----------------------");
        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));
        System.out.println("----------------------");
        System.out.println(person);
        return "hello Spring Boot !";
    }
}

SpringBootInitApplication

@SpringBootApplication
public class SpringBootInitApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootInitApplication.class, args);
    }
}

结果 :

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值