1. 程式人生 > >java讀取properties檔案

java讀取properties檔案

1.通過java.util.Properties提供的getProperty()方法

/**
 * ConfigUtils.java
 * Created at 2018-10-16
 * Created by IchimaruGin
 * Copyright (C) 2018 xxxx, All rights reserved.
 */
package com.issrv.qms.util;

import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import com.alibaba.druid.util.StringUtils;

/**
 * <p>ClassName: ConfigUtils</p>
 * <p>Description: 配置資訊獲取工具</p>
 * <p>Author: IchimaruGin</p>
 * <p>Date: 2018-10-16</p>
 */
public class ConfigUtils {
    /** 載入config配置的Resource */
    private static Resource resource = new ClassPathResource("/config.properties");

    /**
     * <p>Description: 獲取上傳伺服器路徑</p>
     * @param pathKey 路徑的憑藉
     * @return 伺服器上傳路徑
     * @throws IOException 檔案異常
     */
    public static String getRealPath(String pathKey) throws IOException {
        if (StringUtils.isEmpty(pathKey)) {
            return null;
        }
        Properties props = PropertiesLoaderUtils.loadProperties(resource);
        return props.getProperty(pathKey);
    }
}

2.通過註解的方式

首先要在spring-mvc.xml中加入

<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true"/>

然後在要獲取配置資訊的屬性上使用@Value("${propertyKey}")

@Value("${ISSUE_ATTACHMENT_PATH}")
private String issueAttachmentPath;

補上配置properties檔案內容

#客戶司標上傳伺服器路徑
CUSTOMER_LOGO_PATH = D:/upload/image/customer/
#供應商司標上傳伺服器路徑
SUPPLIER_LOGO_PATH = D:/upload/image/supplier/
#問題圖片上傳伺服器路徑
ISSUE_IMAGE_PATH = D:/upload/image/question/
#問題附件上傳伺服器路徑
ISSUE_ATTACHMENT_PATH = D:/upload/attachment/question/

本次分享到這裡,在專案中遇到的一些問題方案都會一一記錄下來,方便博友還有自己日後查閱