SpringBoot项目——读取配置文件及自定义配置文件

本文介绍了如何在SpringBoot项目中读取默认配置文件和自定义配置文件。首先讲解了通过application.properties读取属性,并展示了注解@Value的使用。接着详细阐述了创建和绑定自定义配置文件的步骤,包括创建配置文件、将配置绑定到实体类以及在控制器中注册实体类的实例。通过访问特定URL可查看操作结果。
摘要由CSDN通过智能技术生成

一、读取默认配置文件

1、application.properties:

#端口号
server.port=9090
#自定义属性
test.msg=hello

2、用注解@Value读取属性

package com.gui.hello;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class HelloController {
    @Value("${test.msg}")
    private String msg;

    @RequestMapping("/hello")
    public String hello(){
        return msg;
    }
}

3、访问: http://localhost:9090/test/hello
结果:
在这里插入图片描述

<

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果在 SpringBoot 项目读取配置文件时出现乱码,可能是因为编码格式不正确或者文件本身存在编码问题。你可以尝试以下几种方法来解决: 1. 在 `application.properties` 或 `application.yml` 中添加以下配置: ``` spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true ``` 这些配置将确保 Spring Boot 使用正确的编码格式来读取配置文件。 2. 确认配置文件的编码格式是否正确。可以使用 UTF-8 编码格式保存配置文件,并确保在读取文件时指定正确的编码格式。 ``` Properties properties = new Properties(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties"); try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); properties.load(inputStreamReader); } catch (IOException e) { e.printStackTrace(); } ``` 3. 如果以上方法都无法解决问题,可以尝试使用 `native2ascii` 工具将配置文件转换为 ASCII 码,并在读取文件时指定编码格式为 `ISO-8859-1`。 ``` Properties properties = new Properties(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties"); try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "ISO-8859-1"); properties.load(new StringReader(Native2AsciiUtils.ascii2Native(IOUtils.toString(inputStreamReader)))); } catch (IOException e) { e.printStackTrace(); } ``` 希望这些方法可以帮助你解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值