SpringBoot在工具类中读取配置文件(ClassPathResource)

1、创建配置文件(application.properties)

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

2、创建工具类(PropertiesUtil.java)

复制代码
package com.jeff.utils;

import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class PropertiesUtil {

    private static String user;

    static {
        System.out.println("application.properties属性文件读取开始");
        ClassPathResource resource = new ClassPathResource("application.properties");
        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            user = properties.getProperty("spring.activemq.user");
            System.out.println("user的值:" + user);
        } catch (IOException e) {
            System.out.println("application.properties属性文件读取异常" + e);
        }
        System.out.println("application.properties属性文件读取完成");
    }

    public static String getUser() {
        System.out.println("获取user的值:" + user);
        return user;
    }

}
复制代码

3、创建测试类(MyController.java)

复制代码
package com.jeff.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jeff.utils.PropertiesUtil;

@RestController
public class MyController {

    @RequestMapping("myTest")
    public String myTest() {
        PropertiesUtil.getUser();
        return "success";
    }

}
复制代码

4、打开浏览器访问 http://localhost:8080/myTest,控制台输出结果

 

 

posted @   47号Gamer丶  阅读(1632)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示