zoukankan      html  css  js  c++  java
  • 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,控制台输出结果

     

  • 相关阅读:
    Penetration Test
    SpringBoot启动时初始化数据库及spring.jpa.generate-dll与spring.jpa.hibernate.ddl-auto之间的困惑
    maven deploy到ftp服务器
    spring-boot:repackage生成的MANIFEST.MF中的Main-Class和Start-Class
    @GeneratedValue的strategy
    mysql方言设置
    jpa.generate-ddl和jpa.hibernate.ddl-auto
    在家学习VS在咖啡馆学习
    StatusLogger No Log4j 2 configuration file found
    tomcat应用部署顺序
  • 原文地址:https://www.cnblogs.com/47Gamer/p/13963399.html
Copyright © 2011-2022 走看看