【JavaEE】SpringBoot配置文件的设置及其读取

本文详细介绍了SpringBoot中配置文件的作用,如数据源、日志、缓存等配置,并对比了properties和yml两种格式的用法、优缺点。通过@Value和@ConfigurationProperties注解展示了如何读取配置信息。同时提到了环境特定配置文件的读取方法。

目录

配置文件作用

配置文件注意事项

properties

用法

修改字符集

优缺点

yml

用法

优缺点

读取配置文件

使用 @Value注解

读properties配置文件

 读yml配置文件

使用 @ConfigurationProperties 注解

读properties配置文件

读yml配置文件


配置文件作用

SpringBoot的配置文件主要有以下几个作用:

  1. 数据源和持久化:连接数据库、连接池等各种数据源和持久化相关的配置
  2. 日志记录和调试:设置日志记录级别、格式和输出位置等,还有启用远程调试功能等
  3. 缓存管理:设置缓存文件的类型、过期时间等
  4. Web服务配置:设置Web服务器的端口号、静态资源目录和错误页面等
  5. 安全认证:配置身份验证、授权和HTTP等相关安全配置
  6. 消息服务和异步操作:配置异步消息队列、任务调度等各种消息服务和异步处理功能

配置文件注意事项

  1. 必须要有一个主配置文件,名字只能是application.yml(properties)
  2. 每个平台都必要要有一个配置文件
    命名格式只能是 application-XXX.yml(.properties)
                                       只有XXX部分是自定义的
  3. 若各个配置文件中有完全相同的部分,则统一都写到主配置文件中去
  4. 在Java中,配置文件有两种类型:properties和yml,二者理论上可以出现在同一个项目中,但实际开发中只能统一选一个。
  5. properties的优先级较高,原因是properties和yml本质上没有任何区别,都是键值对,系统率先加载yml的,然后加载properties的,这样properties就会覆盖yml的

properties

Properties 是一种常见的配置文件类型,其以键值对(key-value)的形式保存配置信息。Properties 格式的文件通常使用 .properties 后缀名,该文件包含了若干行文本和 ASCII 编码的字符集,其中每一行都表示一个属性的键值对。在 Java 应用程序中,Properties 类也提供了一套 API 来解析和读取这类文件。

用法

这里就修改了服务器的端口号。

更多的用法可以到这里查看Common Application Properties (spring.io)


修改字符集

在properties中可以 用 # 来写注释

通常在IDEA中的properties的字符集是不适配中文的,这就需要我们修改一下。

 


优缺点

优点:

  1. 写法简单,不易出错,就是 key=value ,对于空格之类的也没有要求
  2. 优先级高

缺点:

  1. 冗余性较大
  2. 只能适用于Java项目,无法对其他语言项目适用

特点:是系统默认的配置文件


yml

yml是YAML的缩写,Yet Another Markup Language(另一种标记语言)

它被广泛应用于各种编程语言中,并且比 JSON 和 XML 更加人性化。

用法

优缺点

优点:

  1. 可读性高:语法简洁,易读
  2. 层级结构分明清晰
  3. 支持更多的数据类型
  4. 可以在各种编程语言的项目中使用

缺点:

  1. 学习成本较高,需要掌握其语法规则

读取配置文件

读取配置文件信息的方法有很多,下面将介绍一些常见的方法。


使用 @Value注解

这个注解可以读取单个配置项

读properties配置文件

package com.example.demo.component;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ReadProperties {
    @Value("${server.port}")
    private String propertiesString;

    @PostConstruct
    public void getPropertiesString() {
        System.out.println("读取properties类型的配置文件信息" + propertiesString);
    }
}

 

 读yml配置文件

package com.example.demo.component;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ReadYml {
    // 必须使用 ${} 才能从配置文件中读出来
    @Value("${server.port}")
    private String ymlString;

    @PostConstruct
    public void getYmlString() {
        System.out.println("读取yml类型的配置文件信息" + ymlString);
    }
}

 

 


使用 @ConfigurationProperties 注解

与@value不同的是,这个@configurationProperties可以读取多个配置项

读properties配置文件

首先要有一个与之对应的Bean对象,该对象的属性名要和配置文件的Key相同才可以

其中prefix的内容是从配置文件中的哪个路径去找,多级下的使用 .  来分开,yml也是同理

package com.example.demo.repository;

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

@Repository
@ConfigurationProperties(prefix = "spring.datasource")
@Data
public class SpringDatasource {
    private String url;
    private String username;
    private String password;
}
package com.example.demo;

import com.example.demo.repository.SpringDatasource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements InitializingBean {

	@Autowired
	private SpringDatasource springDatasource;

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


	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println(springDatasource);
	}
}

读yml配置文件

读取的方法和properties相同。


指定文件来读取

以上两个读取配置文件的方法默认读取的是主配置文件中的内容。若是想要读取 环境特定的配置文件,就需要和 @PropertySource 一起使用了。

使用 @PropertySource 注解 来 指定查询配置文件

通过该注解可以指定读取的位置,然后读取出来配置项。

package com.example.demo;

import com.example.demo.repository.SpringDatasource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("classpath:application-dev.yml")
public class DemoApplication implements InitializingBean {

//	@Autowired
//	private SpringDatasource springDatasource;

	@Value("${server.port}")
	private String port;

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


	@Override
	public void afterPropertiesSet() throws Exception {
//		System.out.println(springDatasource);
		System.out.println(port);

	}
}

读取@ConfigurationProperties同上,只需要在加上该注解指定位置即可。


有什么问题评论区支持。希望可以帮到你。

### 回答问题:不使用 Spring Boot配置文件是怎么生效的? 在 **不使用 Spring Boot** 的传统 Java Web 项目中(如基于 Spring MVC + Servlet 的项目),配置文件的加载和生效是通过 **显式配置 + 容器初始化机制** 来完成的。与 Spring Boot 的“自动配置”不同,这种方式需要开发者手动编写大量的 XML 或 Java Config 配置,并明确告诉 Spring 框架去哪里读取配置、如何解析、何时加载。 --- #### ✅ 一、典型配置文件类型(传统 Spring 项目) | 文件名 | 用途 | |--------|------| | `applicationContext.xml` | Spring 核心配置文件(Bean 定义、数据源、事务等) | | `spring-mvc.xml` | MVC 相关配置(控制器映射、视图解析器、消息转换器) | | `web.xml` | Java EE 标准部署描述符,用于启动 Spring 容器 | | `jdbc.properties` / `config.properties` | 外部属性文件(数据库连接信息等) | --- #### ✅ 二、配置文件生效的核心流程 > 在没有 Spring Boot 的情况下,配置文件生效依赖以下关键组件: 1. **`web.xml` 启动 Spring 容器** 2. **`ContextLoaderListener` 加载主上下文** 3. **`DispatcherServlet` 初始化 MVC 上下文** 4. **PropertyPlaceholderConfigurer 或 `<context:property-placeholder>` 加载 `.properties` 文件** --- ### 🔧 示例:传统 Spring MVC 项目中配置文件是如何生效的 #### 1. `web.xml` —— 应用入口配置 ```xml <!-- web.xml --> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1"> <!-- 1. 启动 Spring 核心容器(Service, DAO 等 Bean) --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 2. 配置 Spring MVC 的 DispatcherServlet --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` > 📌 解释: - `ContextLoaderListener` 会根据 `contextConfigLocation` 参数加载 `applicationContext.xml` - `DispatcherServlet` 加载 `spring-mvc.xml`,创建 Web 层上下文 - 两个上下文形成父子关系,共享 Bean --- #### 2. `applicationContext.xml` —— 主配置文件 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.example.service, com.example.dao"/> <!-- 引入外部 properties 文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 数据源 Bean --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` > 📌 关键点: - `<context:property-placeholder location="classpath:jdbc.properties"/>` 告诉 Spring 去加载这个文件 - `${jdbc.driver}` 这样的占位符会被自动替换为实际值 --- #### 3. `jdbc.properties` —— 外部配置文件 ```properties # jdbc.properties jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC jdbc.username=root jdbc.password=123456 ``` > ✅ 此时,在 `applicationContext.xml` 中引用 `${xxx}` 就能获取这些值。 --- #### 4. `spring-mvc.xml` —— MVC 配置 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描控制器 --> <context:component-scan base-package="com.example.controller"/> <!-- 启用注解驱动(支持 @RequestMapping, @RequestBody 等) --> <mvc:annotation-driven/> <!-- 视图解析器(JSP) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 静态资源处理 --> <mvc:default-servlet-handler/> </beans> ``` --- #### 5. 控制器示例(验证配置是否生效) ```java @RestController public class HelloController { @Value("${jdbc.url}") private String dbUrl; @GetMapping("/hello") public String hello() { return "Database URL: " + dbUrl; } } ``` 访问 `/hello` 输出: ``` Database URL: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC ``` ✅ 表明:`.properties` 文件中的配置已成功注入! --- ### ✅ 总结:传统项目中配置文件生效的关键步骤 | 步骤 | 操作 | 工具/标签 | |------|------|-----------| | 1️⃣ | 编写 `web.xml` | 定义 `ContextLoaderListener` 和 `DispatcherServlet` | | 2️⃣ | 指定 Spring配置文件路径 | `<context-param><param-name>contextConfigLocation</param-name></context-param>` | | 3️⃣ | 创建 `applicationContext.xml` | 使用 `<context:property-placeholder>` 加载 `.properties` 文件 | | 4️⃣ | 使用 `${key}` 占位符 | 在 XML 中引用外部配置 | | 5️⃣ | 使用 `@Value` 注解 | 在 Java 类中注入配置值 | > ⚠️ 注意事项: - 必须确保 `jdbc.properties` 放在 `src/main/resources` 下,才能被 `classpath:` 正确加载 - 如果未配置 `<context:property-placeholder>`,`${}` 占位符不会被解析,导致错误 - XML 文件中的命名空间必须正确引入,否则标签无效 --- ### ✅ 对比:Spring Boot 如何简化这一过程? | 功能 | 传统 Spring | Spring Boot | |------|-------------|--------------| | 配置文件名 | `applicationContext.xml`, `spring-mvc.xml` | `application.yml` 或 `application.properties` | | 配置加载 | 手动指定路径 | 自动从 `classpath:/application.*` 加载 | | 占位符支持 | 需要 `<context:property-placeholder>` | 默认支持 | | 组件扫描 | 手动 `<context:component-scan>` | `@SpringBootApplication` 自动扫描 | | 内嵌服务器 | 无,需部署到 Tomcat | 内置 Tomcat,直接运行 main 方法 | | 启动方式 | 部署 WAR 包 | `java -jar app.jar` | 👉 Spring Boot 的优势在于:**去除了 XML 配置和繁琐的 `web.xml` 设置,实现了自动化配置**。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值