• SpringBoot使用配置文件若干方式


    前言

    在软件开发过程中,经常会使用到配置文件,本文基于SpingBoot如何引入相关的配置项的几种常规方式。

    一、使用@Value引入

    在需要引入配置信息的Bean类中,使用@Value注解可以方便引入对应配置项的内容,但需要将引入配置项的key全名填写正确。
    application.properties

    userproperties.name=this is my user
    
    • 1

    application.yml

    useryml:
    	name:	this is my user
    
    • 1
    • 2
    @Component
    public class UserService{
        @Value("${userproperties.name}")
        private String name;
        @Value("${useryml.name}")
        private String nameyml;
        ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    如上在userService中通过注解@Value则可以引入

    二、使用ConfigurationProperties引入

    注解ConfigurationProperties是使用配置最常见的一种方法,该注解可以统一指定配置的前缀,默认拼接前缀和字段名作为配置项的key,避免手动埴写配置Key名称。

    @Setter
    @Component
    @ConfigurationProperties(prefix = "userproperties")
    public class UserAppConfig{
        private String name;
        private String age;
        private String email;
        private String sex;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    需要注意的是该类中需要提供配置项的set方法,以及标注为Component,当然更多地使用@Configuration取代,其里面也用到了Component。如果不标注为Component,则需要在启动类上显示指定配置类(可以指定多个),通过注解:

    EnableConfigurationProperties(UserAppConfig.class)
    
    • 1

    但需要注意的是UserAppConfig可以通过@Autowired引用,但注意此时无法通过名字获得到Bean。

    三、使用Environment

    默认的配置文件,最终都会统一在Environment进行维护,可以通过其提供的getProperty获得具体的配置值。

     	@Autowired
        private Environment environment;
    
        @PostConstruct
        public void postConstruct() {
            String property = environment.getProperty("userproperties.name");
            System.out.println("userproperties.name====" + property);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    四、使用@PropertySource + @Value

    使用注解可以指定配置文件的路径和名称而不一定是默认配置文件,如下:

    @Component
    @PropertySource(value = "classpath:config.properties")
    @Data
    public class MyConfigBean {
        @Value("${myconfig.name}")
        private String name;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    同样地如与@ConfigurationProperties配置,则可以避免配置项key的完整名称填写。

    但需要注意的是@PropertySource是不支持yaml读取的。需要如下修改:

    import org.springframework.boot.env.YamlPropertySourceLoader;
    import org.springframework.core.env.PropertySource;
    import org.springframework.core.io.support.DefaultPropertySourceFactory;
    import org.springframework.core.io.support.EncodedResource;
    import org.springframework.core.io.support.PropertySourceFactory;
    import org.springframework.lang.Nullable;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Optional;
    
    public class CommPropertyResourceFactory implements PropertySourceFactory {
    
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource
            resource) throws IOException {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) {
            List<org.springframework.core.env.PropertySource<?>> yamlSources = 
                new YamlPropertySourceLoader().load(resourceName, resource.getResource());
            return yamlSources.get(0);
        } else {
            return new DefaultPropertySourceFactory()
                .createPropertySource(name, resource);
        }
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在需要读取yaml的时候,要增加factory参数

    @PropertySource(value = { "classpath:configValue.yml" }, 
    factory = CommPropertyResourceFactory.class)
    
    • 1
    • 2
  • 相关阅读:
    快速搭建接口自动化测试框架
    ShopXO商城系统文件上传0Day代审历程
    树的表示——孩子兄弟表示法
    WordPress优化插件多站点管理软件
    cuda流stream,异步任务的管理
    ubuntu20.04 编译内核源码5.15.58
    Unity3D 基础——使用 Vector3.Lerp 实现缓动效果
    记录linux交叉编译samba服务移植至Hi3559AV100
    PTA 7-194 循环结构 —— 中国古代著名算题。趣味题目:物不知其数。
    IOday7
  • 原文地址:https://blog.csdn.net/sunquan291/article/details/117876962