Java 读取application.properties配置文件中配置

Posted big-boss

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 读取application.properties配置文件中配置相关的知识,希望对你有一定的参考价值。

  实际开发中若需要读取配置文件application.properties中的配置,代码如下。例:读取配置文件中name属性配置值:

技术图片

  代码如下:

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

import java.util.Properties;

public class Test 

    /**
     * 通过配置文件名读取内容
     * @param fileName
     * @return
     */
    public static Properties readPropertiesFile(String fileName) 
        try 
            Resource resource = new ClassPathResource(fileName);
            Properties props = PropertiesLoaderUtils.loadProperties(resource);
            return props;
         catch (Exception e) 
            System.out.println("————读取配置文件:" + fileName + "出现异常,读取失败————");
            e.printStackTrace();
        
        return null;
    

    public static void main(String[] args) 
        Properties properties = readPropertiesFile("application.properties");
        System.out.println(properties.getProperty("name"));
    

  执行结果:

技术图片

 

以上是关于Java 读取application.properties配置文件中配置的主要内容,如果未能解决你的问题,请参考以下文章

springboot学习入门简易版八---springboot2.0多环境配置整合mybatis mysql8+(19-20)

spring boot+kafka整合(未完待续)

使用 Spring Boot 配置 H2 的 Web 控制台

XXL-JOB告警消息推送改造

java文件如何读取

java 读取DLL 咋弄?