Springboot項目根據Key獲取properties中的value值


1、在springboot項目中的resources創建properties文件

 

2、配置你需要的key=value

Login=登錄
UpdatePassword=修改密碼

 

3、創建PropertitesUtil類讀取文件,根據key獲取value

import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Properties;

public class PropertitesUtil extends BaseAction {
    public static Properties props;

    static {
        try {
            readPropertiesFile("/method.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Properties readPropertiesFile(String filePath) throws FileNotFoundException, IOException {
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            InputStream inputStream = classPathResource.getInputStream();
            props = new Properties();
            props.load(new InputStreamReader(inputStream, "UTF-8"));
            return props;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getPropertys(String key) {
        String methodName = props.getProperty(key);
        return methodName;
    }

}

 

4、pom.xml文件配置

<resources></resources>標簽中需要配置文件,否則會出現讀取不到的問題
 <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <includes>
                    <include>mybatis/*</include>
                    <include>application.yml</include>
                    <include>log4j.properties</include>
                    <include>method.properties</include>
                    <include>i18n/*</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>${project.basedir}/src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
           </resource>
  </resources>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM