2017-03-13 64 views
2

我想用屬性文件中的公共靜態最終字段創建Constants類。 問題是ClassLoader始終爲空,我無法獲得屬性文件InputStream。屬性文件中的Spring和Constants類

我使用的是Spring Java Configuration,我知道@PropertySource和@Value spring註解,但我認爲舊式的Constants類在代碼中更具可讀性。

@Autowired 
Constants constants;//in every class that needs constant 
//... 
constants.getArticleLimit() 

VS簡單

Constants.ARTICLES_LIMIT //static var version 

這裏是我的代碼:

package org.simpletest.utils 

import org.apache.log4j.Logger; 

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

public class Constants { 

    private static final Logger LOG = Logger.getLogger(Constants.class); 

    public static final int ARTICLES_LIMIT; 

    public static final String PROPERTIES_LOCATION = "constants.properties"; 

    static { 
     Properties p = new Properties(); 

     //default values 
     int articlesLimit = 10; 

     Class<?> clazz = Constants.class.getClass(); 

     ClassLoader cl = clazz.getClassLoader(); 

     //try to load from properties file 
     try(final InputStream is = cl.getResourceAsStream(PROPERTIES_LOCATION)){ 

      p.load(is); 

      articlesLimit= Integer.parseInt(p.getProperty("articleslimit")); 

     } catch (IOException e) { 
      LOG.debug(String.format("Unable to load {0} properties file. Getting constants by default values.",PROPERTIES_LOCATION),e); 
     } 

     ARTICLES_LIMIT = articlesLimit; 
    } 
} 
+0

爲什麼你不使用@Environment從屬性文件讀取? –

+0

如果您在上下文中使用PropertyPlaceholder,則可以直接在Spring bean中使用屬性值。請參閱http://stackoverflow.com/questions/9259819/how-to-read-values-from-properties-file –

+0

@MichaelPeacock,如果我正確理解這將迫使我在每個使用它們的類中添加所有常量。 –

回答

1

位的測試之後,這是問題:

System.out.println(Constants.class.getClass()); 

這將打印java.lang.Class,它可能尚未由類加載器加載。這是因爲SomeClass.class的等級爲java.lang.class

刪除getClass()並且類加載器不會爲空。不需要clazz變量。這應該是你需要做的所有事情:

ClassLoader cl = Constants.class.getClassLoader(); 
+0

謝謝,這有幫助。 –