Springboot读取properties配置文件

本文介绍了在SpringBoot中读取配置文件的三种方法:1) 使用@ConfigurationProperties和@PropertySource结合,2) 使用@Value直接注入,3) 通过Environment获取。详细步骤包括创建配置文件、定义实体类、编写读取方法,并提供了相关依赖。

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

话不多说上代码*·*

第一种方式任意properties文件@ConfigurationProperties和@PropertySource结合使用

1.创建配置文件
在这里插入图片描述
在这里插入图片描述

2.创建实体类配置类
在这里插入图片描述


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



//配置类
@Configuration
//配置文件的前缀,没有前缀可以不写
@ConfigurationProperties(prefix = "study", ignoreUnknownFields = false)
//配置文件的路劲
@PropertySource("classpath:config/my.properties")
//用于省略get/set方法@Data注解整合了,代码变得简便
@Data
@Component
public class ReadConfFile {
    //配置文件里的属性:name
    private  String name;
    
}

3.写方法读取配置文件内容
在这里插入图片描述

import com.example.studydemo.conffiles.ReadConfFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudyDemoController {

    @Autowired
    private ReadConfFile readConfFile;

    /*
    * 读取配置文件
    * */
    @RequestMapping("/TestMethod1")
    public String TestMethod1(){
        return  readConfFile.getName();
    }
}

4.成功!
在这里插入图片描述

注:附maven依赖

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

第二种方式@Value
在这里插入图片描述
在这里插入图片描述

 //第二种方式:@Value--读取核心配置文件application.properties
    @Value("${database.password}")
    private String password;

    @RequestMapping("/TestMethod2")
    public String TestMethod2(){
        return   "第二种方式"+password;
    }

在这里插入图片描述

第三种方式Environment

//第三种方式:Environment--读取核心配置文件application.properties
    @Autowired
    private Environment env;

    @RequestMapping("/TestMethod3")
    public String TestMethod3(){
        return  "第三种方式"+env.getProperty("database.password");
    }

配置文件同第二种方式

在这里插入图片描述
--------------------------end-------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值