项目外部 property文件使用方法

web.xml

<env-entry>
<env-entry-name>TestConfigs</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>/app/conf/server/api.properties</env-entry-value>
</env-entry>

java代码:

 

public class ConfigUtils {

private final static ConfigUtils INSTANCE = new ConfigUtils();

public static ConfigUtils getInstance() {
return INSTANCE;
}
private static final String MAX_BALANCE = "maxbalance";//"100";


public String getRedenvelopeUnvaliMaxBalance() {
return getProperties().getProperty(MAX_BALANCE);
}

public static Properties props = null;

public static Properties getProperties() {

if (props == null) {
props = new Properties();
InputStream fileStream = null;
Context env = null;
String path = null;
try {
// Get a handle to the JNDI environment naming context
env = (Context) new InitialContext().lookup("java:comp/env");
path = (String) env.lookup("TestConfigs");

File file = new File(path);
file = file.getAbsoluteFile();
fileStream = new FileInputStream(file);

if (logger.isDebugEnabled()) {
logger.debug("Opened config file <" + path
+ "> successfully.");
}
} catch (FileNotFoundException e1) {
logger.error(path
+ " is not found in local environment. Trying the classpath....");
// do nothing yet
} catch (NamingException e) {
logger.error(path + " pathname is erroneous. ", e);
}

try {
if (fileStream == null) {
props.load(ConfigUtil.class.getClassLoader()
.getResourceAsStream(path));
} else {
// HOSTSFILE was found
props.load(fileStream);
}
} catch (IOException e) {
logger.fatal("Cannot find and load " + path
+ "!! Make sure it is available!", e);
}
}
return props;
}

}

Mark:涉及到的知识,jndi、java.until.Properties、 ConfigUtil.class.getClassLoader()
.getResourceAsStream 用法

 

posted @ 2018-03-01 16:49  LandauNi  阅读(137)  评论(0编辑  收藏  举报