Spring Boot教程第2篇:配置文件详解

取自定义属性

在application.yml自定义一组属性:

my:
  name: linjb
  age: 18
  number: ${random.int}

在类中取出:

@RestController
public class HelloController {
    @Value("${my.name}")
    private String name;
    @Value("${my.age}")
    private int age;
    @Value("${my.number}")
    private int number;
    @RequestMapping(value = "/hi")
    public String hello(){
        return name+ ":" + age + ":" + number;
    }
}

配置文件赋值给bean

ConfigBean.java

@ConfigurationProperties(prefix = "my")
@Component
public class ConfigBean {
    private String name;
    private int age;
    private int number;

    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 getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "ConfigBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", number=" + number +
                '}';
    }
}

HelloController.java

@Autowired
private ConfigBean configBean;

@RequestMapping("/hello")
public String hello(){
    return configBean.toString();
}

访问/hello可以读取值

使用自定义配置文件

test.properties

tk.amrom.name=linjb
tk.amrom.age=200
tk.amrom.number=${random.int}

ConfigBean.java

@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "tk.amrom")
@Component
public class ConfigBean {
    private String name;
    private int age;
    private int number;
	//geter seter
}

多个环境配置文件

在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.yml,其中{profile}对应你的环境标识,比如:

  • application-test.yml:测试环境
  • application-dev.yml:开发环境
  • application-prod.yml:生产环境

使用:在application.yml中加

spring:
  profiles:
    active: dev