SpringBoot项目加载配置文件的6种方式小结

 更新时间:2023年09月18日 11:17:41   作者:Roue治愈者ヅ聶  
这篇文章给大家总结了六种SpringBoot项目加载配置文件的方式,通过@value注入,通过@ConfigurationProperties注入,通过框架自带对象Environment实现属性动态注入,通过@PropertySource注解,yml外部文件,Java原生态方式注入这六种,需要的朋友可以参考下

1、通过@value注入

满足条件:

1、该类首先要被SpringBoot框架管理,属于SpringBoot框架的Bean。

2、application.properties(或者application.yml)配置文件中存在该配置名。(如果不存在可以加冒号,框架会赋值默认值,也可以在冒号后面自定义默认值。例如:test.domain:)。配置文件中不包含该配置,注解中也没加冒号,项目启动就会报错。

3、被static和finely修饰的属性配置该注解不会生效。

@Component
public class BaseConfig {
    @Value("${test.domain:}")
    private String domamin;
    @Value("${test.api:}")
    private String api;
}

2、通过@ConfigurationProperties注入

1、该类首先要被SpringBoot框架管理,属于SpringBoot框架的Bean。

2、@ConfigurationProperties进行指定配置文件中key的前缀。进行自动装配属性。适用于批量绑定,批量注入属性值。相比@value更省事。

 #application.yml配置文件
es:
  post:9200
  host:localhost
  name:es
@Data
@Component
@ConfigurationProperties(prefix="es")
public class ESProperties {
    private String host;
    private String name;
    private int port;
}

3、通过框架自带对象Environment实现属性动态注入

#application.yml配置文件
es:
  post:9200
  host:localhost
  name:es

方式一:容器自动注入SpringBoot框架自带的类Environment进行实现动态配置属性值注入。

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class EsProperties {
    private String host;
    private String name;
    private int post;
    @Resource
    private Environment environment;
    public String getHost() {
        return environment.getProperty("es.host");
    }
    public String getName() {
        return environment.getProperty("es.name");
    }
    public int getPost() {
        String post = environment.getProperty("es.post");
        return Integer.parseInt(post);
    }
}

方式二:自己实现EnvironmentAware接口进行重写方法进行注入Environment。好处可以和spring boot框架的解耦性更低一点。

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class EsProperties implements EnvironmentAware {
    private String host;
    private String name;
    private int post;
    private Environment environment;
    public String getHost() {
        return environment.getProperty("es.host");
    }
    public String getName() {
        return environment.getProperty("es.name");
    }
    public int getPost() {
        String post = environment.getProperty("es.post");
        return Integer.parseInt(post);
    }
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

4、通过@PropertySource注解实现外部配置文件注入属性值

#es.properties配置文件
es.post=9200
es.host=localhost
es.name=es

1、通过@PropertySource注解实现导入外部配置文件。

2、配合@value注解实现属性注入或者@ConfigurationProperties注解实现批量注入。

3、该方式只能获取 .properties 的配置文件不能获取 .yml 的配置文件。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:es.properties",encoding = "utf-8")
public class EsProperties {
    @Value("${es.host}")
    private String host;
    @Value("${es.name}")
    private String name;
    @Value("${es.post}")
    private int post;
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:es.properties",encoding = "utf-8")
@ConfigurationProperties(prefix = "es")
public class EsProperties {
    private String host;
    private String name;
    private int post;
}

5、yml 外部配置文件动态注入

第4中方式只能实现 .properties 文件的,该方式是实现 .yml 文件的。

1、自定义配置类,实例化PropertySourcesPlaceholderConfigurer类,使用该类进行属性值的注入。

2、实例化完PropertySourcesPlaceholderConfigurer类之后,就可以配合@value注解实现属性注入或者@ConfigurationProperties注解实现批量注入。

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import java.util.Objects;
@Configuration
public class MyYmlConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer yamlConfigurer(){
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("es.yml"));
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class EsProperties {
    @Value("${es.host}")
    private String host;
    @Value("${es.name}")
    private String name;
    @Value("${es.post}")
    private int post;
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "es")
public class EsProperties {
    private String host;
    private String name;
    private int post;
}

6、Java原生态方式注入属性值

#es.properties配置文件
es.post=9200
es.host=localhost
es.name=es
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
@Component
public class EsProperties {
    private String host;
    private String name;
    private int post;
    @Bean
    public void init(){
        Properties props = new Properties();
        InputStreamReader inputStreamReader = new InputStreamReader(
                this.getClass().getClassLoader().getResourceAsStream("es.properties"), StandardCharsets.UTF_8);
        try {
            props.load(inputStreamReader);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        this.host = props.getProperty("es.host");
        this.name = props.getProperty("es.name");
        this.post = Integer.parseInt(props.getProperty("es.post"));
    }
}

以上就是SpringBoot项目加载配置文件的6种方式小结的详细内容,更多关于SpringBoot加载配置文件的资料请关注脚本之家其它相关文章!

相关文章

  • 通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端的操作方法

    通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端的操作方法

    这篇文章主要介绍了通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • Java读写锁ReadWriteLock原理与应用场景详解

    Java读写锁ReadWriteLock原理与应用场景详解

    这篇文章主要介绍了Java读写锁ReadWriteLock原理与应用场景详解,读写状态的设计,写锁的获取与释放,锁降级需要的朋友可以参考下
    2023-02-02
  • java使用Feign实现声明式Restful风格调用

    java使用Feign实现声明式Restful风格调用

    这篇文章主要为大家详细介绍了java使用Feign实现声明式Restful风格调用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-04-04
  • Java流式操作之Collectors工具类操作指南

    Java流式操作之Collectors工具类操作指南

    Collectors是Collector的工具类,类中提供了很多流收集、归约、分组、分区等方法,方便我们直接使用,下面这篇文章主要给大家介绍了关于Java流式操作之Collectors工具类操作的相关资料,需要的朋友可以参考下
    2023-05-05
  • 如何设置springboot禁止日志输出到控制台

    如何设置springboot禁止日志输出到控制台

    文章总结:本文主要介绍了SpringBoot项目中使用SLF4J记录日志时,日志默认输出到控制台的原因及解决方法,日志框架如Logback默认会将日志输出到控制台,可以通过`logback-spring.xml`配置文件或配置类来禁止日志输出到控制台,并设置日志输出级别
    2025-01-01
  • 详解用Eclipse如何创建Web项目

    详解用Eclipse如何创建Web项目

    本篇文章主要介绍了详解用Eclipse如何创建Web项目,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • 一篇文章带你理解Java的SPI机制(图文并茂)

    一篇文章带你理解Java的SPI机制(图文并茂)

    本文详细介绍了Java的SPI机制,包括其定义、用途和实现方式,SPI(ServiceProviderInterface)是一种服务发现机制,用于实现框架或库的扩展点,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-10-10
  • 基于Java实现XML文件的解析与更新

    基于Java实现XML文件的解析与更新

    配置文件可以有很多种格式,包括 INI、JSON、YAML 和 XML。每一种编程语言解析这些格式的方式都不同。本文将通过Java语言实现XML文件的解析与更新,需要的可以参考一下
    2022-03-03
  • Java中StringBuilder常用构造方法解析

    Java中StringBuilder常用构造方法解析

    这篇文章主要介绍了Java中StringBuilder常用构造方法解析,StringBuilder是一个可标的字符串类,我们可以吧它看成是一个容器这里的可变指的是StringBuilder对象中的内容是可变的,需要的朋友可以参考下
    2024-01-01
  • java生成XML的方法【附demo源码下载】

    java生成XML的方法【附demo源码下载】

    这篇文章主要介绍了java生成XML的方法,涉及java针对xml格式文件的简单操作技巧,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2016-12-12

最新评论