使用IDEA创建Springboot项目,默认会在resource目录下创建application.properties文件,也可以使用yml类型的配置文件代替properties文件,下面我们具体介绍:

1.配置文件(.properties或.yml):

application.properties
Spring Boot(二)项目目录和简单配置

application.yml
Spring Boot(二)项目目录和简单配置
两个配置内容是一致的,只不过显示和排版不一样。

2.将配置文件的属性赋给实体类

第一种直接写在application.yml中

my:
 name: forezp
 age: 12
 number: 11

创建一个类,将值赋予
需要加个注解@ConfigurationProperties,并加上它的prrfix。另外@Component可加可不加

@ConfigurationProperties(prefix = "my")
@Component
public class UserBean {
 	private String name;
    private int age;
    private int number;
    private String uuid;
	......省略......

如果需要在应用类或者application类引用,加EnableConfigurationProperties注解

@RestController
@EnableConfigurationProperties({UserBean .class})
public class UserController {
    @Autowired
    private UserBean userBean;

    @RequestMapping(value = "/user")
    public String userInfo(){
      return userBean.getName()+userBean.getAge();
    }

如果需要自定义文件则在@ConfigurationProperties前面加上文件目录
比如读取Resources目录的test.properties

@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "my")
@Component
public class UserBean {
 	private String name;
    private int age;
    private int number;
    private String uuid;
	......省略......

3.多环境配置文件

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

properties

spring.profiles.active = dev

yml

spring:
  profiles:
    active: dev

参考文献:
SpringBoot 配置文件详解
SpringBoot 配置属性详解

相关文章: