springboot类读取配置文件的两种方法

本文介绍两种在SpringBoot项目中读取配置文件的方法:一是使用@Value注解直接注入属性值;二是通过@ConfigurationProperties进行数据绑定,实现更优雅的配置读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一

目录结构

首先要编写application类,添加一些值

com:
  ning:
    value: hello
    name: zhangsan

server:
  servlet:
    context-path: /yhj
  port: 8888

接下来编写一个类,类中获取配置文件的值

package com.ning.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/boot")
public class Controller {

    @Value("${com.ning.value}")
    private String value;
    @Value("${com.ning.name}")
    private String name;

    @GetMapping("getvalue")
    public void firstConfInject(){
        log.info("first conf inject: {},{}",value,name);
    }
}

从浏览器上发送一个请求,这是控制台打印的日志成功获取到了配置文件的值

 方法二

首先在pom文件中添加一个数据绑定的依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

配置文件不变,编写一个类

package com.ning.config;

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

@Data
@Component
@ConfigurationProperties(prefix = "com.ning")
public class ConfigGetValue {
    private String value;
    private String name;
}

这样,值就获取到了,验证方法是再写一个controller将这个类注入,再获取值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值