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

这篇具有很好参考价值的文章主要介绍了SpringBoot项目加载配置文件的6种方式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

1、通过@value注入

2、通过@ConfigurationProperties注入

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

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

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

6、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文章来源地址https://www.toymoban.com/news/detail-666875.html

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种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Boot如何实现配置文件的自动加载和刷新?

    在使用Spring Boot开发应用程序时,配置文件是非常重要的组成部分。在不同的环境中,我们可能需要使用不同的配置文件,例如在开发、测试和生产环境中使用不同的配置文件。而且,当我们更改配置文件时,我们希望应用程序能够自动加载和刷新配置文件,而无需重启应用

    2024年02月07日
    浏览(50)
  • 企业级信息系统开发——Spring Boot加载自定义配置文件

    设置项目元数据 添加项目依赖 设置项目编码为utf8(尤其注意复选框) 在 resources 下创建 myconfig.properties 文件 在 net.shuai.boot 包里创建配置类 config.StudentConfig 点开测试类 ConfigDemo01ApplicationTests 编写测试方法,注入学生配置实体,创建 testStudentConfig() 测试方法,在里面输出学生

    2024年02月07日
    浏览(34)
  • Spring的加载配置文件、容器和获取bean的方式

    🐌个人主页: 🐌 叶落闲庭 💨我的专栏:💨 c语言 数据结构 javaweb 石可破也,而不可夺坚;丹可磨也,而不可夺赤。 properties文件: jdbc.properties 1.开启context命名空间 2.使用context命名空间,加载指定properties文件 3.使用属性占位符 ${} 读取properties文件中的属性 properties文件

    2024年02月15日
    浏览(30)
  • spring boot项目同时传递参数和文件的多种方式

    在开发接口中,遇到了需要同时接收参数和文件的情况,可以有多种方式实现文件+参数的接收,这里基于spring boot 3 + vue 3 + axios,做一个简单的代码演示。 参数较少时,比较方便,直接参数接受即可 1.1 后端接口 1.2 前端请求 fileAndSimpleParam 为封装的api请求方法,可查看下文的

    2024年02月13日
    浏览(38)
  • Spring Boot学习随笔- @SpringBootApplication详解、加载绝对路径配置文件、工厂创建对象(@ConfigurationProperties、@Value)

    学习视频:【编程不良人】2021年SpringBoot最新最全教程 这是一个 组合注解 ,就是由多个注解组成。下列注解红框内称为 元注解 (jdk提供) @Target :指定注解作用范围 @Retention :指定注解什么时候生效 重要注解 @SpringBootConfiguration:自动配置Spring、SpringMVC相关环境 @EnableAutoCo

    2024年02月05日
    浏览(44)
  • 【Spring Boot学习一】创建项目 && Spring Boot的配置文件

    目录 一、安装插件 二、创建Spring Boot项目 1、创建项目 1.1 使用IDEA创建  1.2 网页版本创建 2、项目目录介绍与运行 三、Sping Boot的配置文件(重点) 🌷1、.properties配置文件 (1)基础语法:Key = value (2)读取配置⽂件中的内容,@Value 注解使⽤“${}”的格式读取; 🌷2、.y

    2024年02月16日
    浏览(31)
  • 17、YML配置文件及让springboot启动时加载我们自定义的yml配置文件的几种方式

    其实本质和.properties文件的是一样的。 Spring Boot默认使用SnakeYml工具来处理YAML配置文件,SnakeYml工具默认就会被spring-boot-starter导入,因此无需开发者做任何额外配置。 YAML本质是JSON的超级,它在表示结构化文档时更有表现力。 ▲ properties文件使用 .分隔符 作为结构化的表现:

    2024年02月14日
    浏览(32)
  • 聊聊Spring Boot配置文件:优先级顺序、加载顺序、bootstrap.yml与application.yml区别详解

    在 Spring Boot 中,配置文件的优先级顺序是: application-{profile}.yml ( application-{profile}.properties ) application.yml ( application.properties ) bootstrap.yml ( bootstrap.properties )。其中, {profile} 表示不同的环境配置,如 dev 、 test 、 prod 等。 优先级从高到低,高优先级的配置覆盖低优先级

    2024年01月25日
    浏览(47)
  • 详解 Spring Boot 项目中的配置文件

    🎉🎉🎉 点进来你就是我的人了 博主主页: 🙈🙈🙈 戳一戳,欢迎大佬指点! 欢迎志同道合的朋友一起加油喔 🤺🤺🤺 目录 1. Spring Boot 项目中配日文件的作用是什么 2. Spring Boot 配置文件的两种格式 1. properties的语法 2. yml的语法 3. properties与yml的对比 4. 设置不同环境下的配

    2024年02月08日
    浏览(40)
  • SpringBoot+jasypt-spring-boot-starter实现配置文件明文加密

    springboot:2.1.4.RELEASE JDK:8 jasypt-spring-boot-starter:3.0.2 Jasypt默认算法为PBEWithMD5AndDES,该算法需要一个加密密钥,可以在应用启动时指定(环境变量)。也可以直接写入配置文件 3.1 application.properties配置文件版 加密后,可删除jasypt.encryptor.password配置;发版时可在命令行中配置 3.2 函数

    2024年02月15日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包