SpringBoot中读取配置文件的几种方式


1.读取application文件

在application.yml或者properties文件中添加:

info:
  name: xiaoming
  age: 13
  sex: 1

读取方式如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/* * 通过@value注解的方式读取 */
@Component
public class TechUser {
    @Value("${info.name}")
    private String name;
    @Value("${info.age}")
    private int age;
    @Value("${info.sex}")
    private int sex;

    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 int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }
}


@ConfigurationProperties注解读取方式

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "info")
public class TechUser {
    private String name;
    private int age;
    private int sex;

    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 int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }
}

2.读取指定文件

资源目录下建立config/db-config.properties:

db.username=root

db.password=123456

2.1@PropertySource+@Value注解读取方式
@Component
@PropertySource(value = { "config/db-config.properties" })
public class DBConfig1 {
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private 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;
    }
}

注意:@PropertySource不支持yml文件读取。

2.2@PropertySource+@ConfigurationProperties注解读取方式
@Component
@ConfigurationProperties(prefix = "db")
@PropertySource(value = { "config/db-config.properties" })
public class DBConfig2 {
    private String username;
    private 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.Environment读取方式

以上所有加载出来的配置都可以通过Environment注入获取到。

@Autowired
private Environment env;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM