SpringBoot 读取配置的几种方式

592 阅读2分钟

SpringBoot中读取项目配置的主要分为两大类,第一种就是直接将配置读取到指定的一个字段上,第二种就是将配置读取到配置类上,然后其他使用到配置的组件装配配置类就可以了

classpath

在介绍SpringBoot读取配置之前,首先有必要了解一下classpath,因为程序默认都是加载classpath目录下面的配置文件

SpringBoot中的classpath其实就是class的路径,也就是springBoot项目编译之后生产的target/classes文件夹,这个文件夹就是对src/main/javasrc/main/resource编译的结果,所以有时候提到classpath也会说是这两个目录

SpringBoot加载配置的顺序

SpringBoot默认加载配置的顺序如下所示:

–file:./config/  // 项目根目录下面的 config 文件夹
–file:./         // 项目根目录下面的配置文件
–classpath:/config/
–classpath:/

当然也可以通过注解去指定配置文件的路径,下面就详细介绍一下程序加载配置的几种方式

SpringBoot加载配置

@Value注解

配置文件:application.properties

```
demo.name=Name
demo.age=18
```

读取文件代码:

```
@RestController
public class GatewayController {
 
    @Value("${demo.name}")  //此处直接读取 application.properties 文件中的 key 就可以了
    private String name;
 
    @Value("${demo.age}")
    private String age;
 
    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                " name=" + name +
                " , age=" + age;
    }
}
```

Enviroment读取配置

配置文件为:application.properties

```
demo.sex=男
demo.address=山东
```

读取配置文件的代码

```
@RestController
public class GatewayController {
    @Autowired
    private Environment environment;
 
    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                // 使用 Environment 读取
                " , sex=" + environment.getProperty("demo.sex") +
                " , address=" + environment.getProperty("demo.address");
    }
}
```

@ConfigurationProperties注解

使用该注解就可以直接将配置文件读取到一个类当中,然后其他组件使用该配置则装配这个类就好了,下面是具体的代码示例:

配置文件为:config.properties,配置的内容如下:

```
demo.phone=10086
demo.wife=self
```

java代码读取配置:

```
@Component
@ConfigurationProperties(prefix = "demo")
@Data
public class ConfigBeanProp {
 
    private String phone;
 
    private String wife;
 
}
```

这样就可以在其他组件中装配此类获取相应的配置了;@ConfigurationProperties指定了配置中的前缀,这样字段就可以与后面的内容进行匹配了

@ConfigurationProperties默认是从application.properties中加载配置的;它也可以与注解@PropertySource一起使用来指定要加载的配置的位置

```
@ConfigurationProperties
@Component
@Data
@PropertySource(value = "config.properties",encoding = "utf-8")
public class Config {
    
    private String name;
​
    private int age;
}
```

使用@PropertySource注解有以下几点需要注意:

  1. @PropertySource默认读取的文件为classpath:application.properties,如果需要更改,则可以通过value指定

  2. @PropertySource默认读取的编码为ios8859-1,所以如果要指定编码可以通过encoding="utf-8"指定

  3. @PropertySource默认读取的文件为.properties,如果要读取.yaml文件则需要重新DefaultPropertySourceFactory,让其加载yaml文件,实现代码如下:

    public class YmlConfigFactory extends DefaultPropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            String sourceName = name != null ? name : resource.getResource().getFilename();
            if (!resource.getResource().exists()) {
                return new PropertiesPropertySource(sourceName, new Properties());
            } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
                Properties propertiesFromYaml = loadYml(resource);
                return new PropertiesPropertySource(sourceName, propertiesFromYaml);
            } else {
                return super.createPropertySource(name, resource);
            }
        }
    ​
        private Properties loadYml(EncodedResource resource) throws IOException {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        }
     }
    

    添加注解为:

    @PropertySource(value = {"classpath:config.properties"},encoding="gbk",factory = YmlConfigFactory.class)