springboot学习(三)加载配置文件

本博文为系列文章建议大家从头阅读

  1. application配置文件
    springboot默认是会加载classpath下的application.yml或application.properties文件的,项目中可以直接使用@Value注解使用其中的配置信息。
    比如我们上一节讲到的profile
    @Value("${spring.profiles.active:dev}")
    private String profile;
  1. 自定义配置文件
    通常我们会把一些全局的配置项放到application中,一些专项配置如db相关的、elasticsearch相关的、大数据相关的配置项单独放到一些配置文件中,我们这里用db进行演示:
    在这里插入图片描述
    mysql.properties的内容如下:
mysql.db_url=jdbc:mysql://localhost:3306/mfcq?useSSL=false&characterEncoding=utf8&serverTimezone=UTC
mysql.db_name=root
mysql.db_password=root

springboot推荐配置项使用Configuration Bean的方式使用,当然也可以使用@PropertySource和@Value,我们以Bean方式为例:
创建MysqlConfig.class类

package com.hero.study.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:properties/${spring.profiles.active}/mysql.properties")
@ConfigurationProperties(prefix = "mysql")
public class MysqlConfig {
    private String dbUrl;
    private String dbName;
    private String dbPassword;

省略getset
}

@PropertySource("classpath:properties/ s p r i n g . p r o f i l e s . a c t i v e / m y s q l . p r o p e r t i e s " ) {spring.profiles.active}/mysql.properties"):配置文件的位置 {spring.profiles.active}为mave编译时指定的环境,我们这里是dev,这里强调一点这个注解是不支持任何通配符的否则会报找不到文件异常
@ConfigurationProperties(prefix = “mysql”):prefix = "mysql"指属性名的前缀,对应mysql.db_name=root、mysql.db_password=root等
springboot会自动把属性中的“_“,” -” 等符号去掉变为java规范名,所以这里db_url对应dbUrl

在我们的demo中添加如下代码查看效果

@RestController
public class DemoController {

    @Resource(name = "mysqlConfig")
    private MysqlConfig mysqlConfig;

    @RequestMapping("/demo")
    public String demo(){
        return "hello world="+mysqlConfig.getDbUrl();
    }
}

访问http://localhost:8080/demo
可以看到:hello world=jdbc:mysql://localhost:3306/mfcq?useSSL=false&characterEncoding=utf8&serverTimezone=UTC

  1. 注意
    @Configuration Bean方式只支持properties文件
    如果想支持yml文件,可以自定义如下类
package com.hero.study.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

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(“classpath:properties/ s p r i n g . p r o f i l e s . a c t i v e / m y s q l . p r o p e r t i e s &quot; ) @ P r o p e r t y S o u r c e ( v a l u e = &quot; c l a s s p a t h : p r o p e r t i e s / {spring.profiles.active}/mysql.properties&quot;) @PropertySource(value = &quot;classpath:properties/ {spring.profiles.active}/mysql.yml”,factory = YmlConfigFactory.class)
mysql.properties改为mysql.yml
在这里插入图片描述
注意属性名和值之间的冒号后必须有一个空格
再次运行访问http://localhost:8080/demo
可以看到:hello world=jdbc:mysql://localhost:3306/mfcq?useSSL=false&characterEncoding=utf8&serverTimezone=UTC

发布了52 篇原创文章 · 获赞 7 · 访问量 3827

猜你喜欢

转载自blog.csdn.net/maomaoqiukqq/article/details/98635957
今日推荐