面试突击75:SpringBoot 有几种读取配置文件的方法?

简介: 面试突击75:SpringBoot 有几种读取配置文件的方法?

Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件。
  2. 使用 @ConfigurationProperties 读取配置文件。
  3. 使用 Environment 读取配置文件。
  4. 使用 @PropertySource 读取配置文件。
  5. 使用原生方式读取配置文件。

它们的具体使用方法如下,为了方便测试,我们在 Spring Boot 配置文件 application.properties 添加以下内容:

profile.name=Spring Boot Profile
profile.desc=Spring Boot Profile Desc.

1.使用 @Value 读取配置文件

使用 @Value 可以读取单个配置项,如下代码所示:

@SpringBootApplication
public class DemoApplication implements InitializingBean {
    @Value("${profile.name}")
    private String name;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("My Profile Name:" + name);
    }
}

以上程序的执行结果如下图所示:
image.png

2.使用 @ConfigurationProperties 读取配置文件

@ConfigurationProperties 和 @Value 的使用略微不同,@Value 是读取单个配置项的,而 @ConfigurationProperties 是读取一组配置项的,我们可以使用 @ConfigurationProperties 加实体类读取一组配置项,如下代码所示:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "profile")
@Data
public class Profile {
    private String name;
    private String desc;
}

其中 prefix 表示读取一组配置项的根 name,相当于 Java 中的类名,最后再把此配置类,注入到某一个类中就可以使用了,如下代码所示:

@SpringBootApplication
public class DemoApplication implements InitializingBean {
    @Autowired
    private Profile profile;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Profile Object:" + profile);
    }
}

以上程序的执行结果如下图所示:
image.png

3.使用 Environment 读取配置文件

Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值了,如下代码所示:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class DemoApplication implements InitializingBean {

    @Autowired
    private Environment environment;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Profile Name:" + environment.getProperty("profile.name"));
    }
}

以上程序的执行结果如下图所示:
image.png

4.使用 @PropertySource 读取配置文件

使用 @PropertySource 注解可以用来指定读取某个配置文件,比如指定读取 application.properties 配置文件的配置内容,具体实现代码如下:

@SpringBootApplication
@PropertySource("classpath:application.properties")
public class DemoApplication implements InitializingBean {
    @Value("${profile.name}")
    private String name;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Name:" + name);
    }
}

以上程序的执行结果如下图所示:
image.png

中文乱码

如果配置文件中出现中文乱码的情况,可通过指定编码格式的方式来解决中文乱码的问题,具体实现如下:

@PropertySource(value = "dev.properties", encoding = "utf-8")

注意事项

@PropertySource 注解默认是只支持 properties 格式配置文件的读取的。

5.使用原生方式读取配置文件

我们还可以使用最原始的方式 Properties 对象来读取配置文件,如下代码所示:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

@SpringBootApplication
public class DemoApplication implements InitializingBean {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Properties props = new Properties();
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("application.properties"),
                    StandardCharsets.UTF_8);
            props.load(inputStreamReader);
        } catch (IOException e1) {
            System.out.println(e1);
        }
        System.out.println("Properties Name:" + props.getProperty("profile.name"));
    }
}

以上程序的执行结果如下图所示:
image.png

总结

在 Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件。
  2. 使用 @ConfigurationProperties 读取配置文件。
  3. 使用 @PropertySource 读取配置文件。
  4. 使用 Environment 读取配置文件。
  5. 使用原生方式读取配置文件。

其中最常用的是前 3 种,如果读取某一个配置项可使用 @Value,如果读取一组配置项可使用 @ConfigurationProperties,如果要指定读取某一个具体的配置文件可使用 @PropertySource 来指定。

是非审之于己,毁誉听之于人,得失安之于数。

公众号:Java面试真题解析

面试合集:https://gitee.com/mydb/interview

相关文章
|
2月前
|
Java 开发者 Spring
【SpringBoot 异步魔法】@Async 注解:揭秘 SpringBoot 中异步方法的终极奥秘!
【8月更文挑战第25天】异步编程对于提升软件应用的性能至关重要,尤其是在高并发环境下。Spring Boot 通过 `@Async` 注解简化了异步方法的实现。本文详细介绍了 `@Async` 的基本用法及配置步骤,并提供了示例代码展示如何在 Spring Boot 项目中创建与管理异步任务,包括自定义线程池、使用 `CompletableFuture` 处理结果及异常情况,帮助开发者更好地理解和运用这一关键特性。
124 1
|
18天前
|
设计模式 Java 关系型数据库
【Java笔记+踩坑汇总】Java基础+JavaWeb+SSM+SpringBoot+SpringCloud+瑞吉外卖/谷粒商城/学成在线+设计模式+面试题汇总+性能调优/架构设计+源码解析
本文是“Java学习路线”专栏的导航文章,目标是为Java初学者和初中高级工程师提供一套完整的Java学习路线。
172 37
|
18天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
7天前
|
Java 应用服务中间件 Spring
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
|
9天前
|
ARouter 测试技术 API
Android经典面试题之组件化原理、优缺点、实现方法?
本文介绍了组件化在Android开发中的应用,详细阐述了其原理、优缺点及实现方式,包括模块化、接口编程、依赖注入、路由机制等内容,并提供了具体代码示例。
26 2
|
2月前
|
Java
【Java基础面试二十】、介绍一下Object类中的方法
这篇文章介绍了Java中Object类的常用方法,包括`getClass()`、`equals()`、`hashCode()`、`toString()`、`wait()`、`notify()`、`notifyAll()`和`clone()`,并提到了不推荐使用的`finalize()`方法。
【Java基础面试二十】、介绍一下Object类中的方法
|
2月前
|
Java API 索引
【Java基础面试二十四】、String类有哪些方法?
这篇文章列举了Java中String类的常用方法,如`charAt()`、`substring()`、`split()`、`trim()`、`indexOf()`、`lastIndexOf()`、`startsWith()`、`endsWith()`、`toUpperCase()`、`toLowerCase()`、`replaceFirst()`和`replaceAll()`,并建议面试时展示对这些方法的熟悉度,同时深入理解部分方法的源码实现。
【Java基础面试二十四】、String类有哪些方法?
|
7天前
|
消息中间件 NoSQL 安全
(转)Spring Boot加载 不同位置的 application.properties配置文件顺序规则
这篇文章介绍了Spring Boot加载配置文件的顺序规则,包括不同位置的application.properties文件的加载优先级,以及如何通过命令行参数或环境变量来指定配置文件的名称和位置。
|
2月前
|
SQL Java 测试技术
SpringBoot单元测试快速写法问题之PorkService 接口中的 getPork 方法的作用如何解决
SpringBoot单元测试快速写法问题之PorkService 接口中的 getPork 方法的作用如何解决
|
2月前
|
Java
【Java集合类面试三十】、BlockingQueue中有哪些方法,为什么这样设计?
BlockingQueue设计了四组不同行为方式的方法用于插入、移除和检查元素,以适应不同的业务场景,包括抛异常、返回特定值、阻塞等待和超时等待,以实现高效的线程间通信。