上面介绍的是我们都把配置文件写到application.yml中。有时我们不愿意把配置都写到application配置文件中,这时需要我们自定义配置文件,比如test.properties:
com.forezp.name=forezp com.forezp.age=12
怎么将这个配置文件信息赋予给一个javabean呢?
@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.forezp")
public class User {
    private String name;
    private int age;
    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;
    }
}
在最新版本的springboot,需要加这三个注解。
@Configuration 
@PropertySource(value = “classpath:test.properties”) 
@ConfigurationProperties(prefix = “com.forezp”);在1.4版本需要 
PropertySource加上location。
@RestController
@EnableConfigurationProperties({ConfigBean.class,User.class})
public class LucyController {
    @Autowired
    ConfigBean configBean;
    @RequestMapping(value = "/lucy")
    public String miya(){
        return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax();
    }
    @Autowired
    User user;
    @RequestMapping(value = "/user")
    public String user(){
        return user.getName()+user.getAge();
    }
}
启动工程,打开localhost:8080/user;浏览器会显示:
forezp12四、多个环境配置文件
在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.properties,其中{profile}对应你的环境标识,比如:
- application-test.properties:测试环境
- application-dev.properties:开发环境
- application-prod.properties:生产环境
怎么使用?只需要我们在application.yml中加:
spring:
  profiles:
    active: dev
其中application-dev.yml:
server: port: 8082
启动工程,发现程序的端口不再是8080,而是8082。
 
        
