SpringBoot 官方文档示例:(12)读取配置文件中属性的3种常用方式

一、SpringBoot读取配置文件里属性的几种方式:
1.通过定义配置类,使用
@Configuration注解和@ConfigurationProperties注解,然后注入该配置类,最后通过配置类的getter方法拿配置
2.通过@value注解
3.通过注入Enviroment bean

二、示例

  1. application.properties
server.port=9070
username=amadeusliu
password=myPassword
school=tju

2.定义配置类:

package cn.edu.tju.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties
@Configuration
public class MyConfig {
    public String username;
    public String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

3.controller中分别用各种方式获取配置属性

package cn.edu.tju.controller;

import cn.edu.tju.config.MyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.env.Environment;

@RestController
public class TestController {
    @Autowired
    Environment environment;
    @Autowired
    private MyConfig myConfig;
    @Value("${school}")
    private String school;

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    @RequestMapping("getSchool")
    public String getInfo(){
        return getSchool();
    }

    @RequestMapping("getPassword")
    public String getPassword(){
        return myConfig.getPassword();
    }
    @RequestMapping("getVmInfo")
    public String getVmInfo(){
        return environment.getProperty("java.vm.info");
    }
}


4.启动程序,访问网址:

http://localhost:9070/getPassword
http://localhost:9070/getSchool
http://localhost:9070/getVmInfo

输出结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值