Monday, June 22, 2015

Reading properties from property util classes


Ex:

application.properties

template_card_image_path=D:/smilesurance-plain.png
hooper_code=234
service_id=01
business_code=SMILIN
images_path=D:/Smiline/cards/
corporate_name=Hackett Group
card_validity=Valid till:

PropertyUtils .java

package com.hps.platform.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hps.platform.utility.service.MessageService;

public class PropertyUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(MessageService.class);
private static PropertyUtils propertyUtilsInstance;
private static Properties properties;

static{
propertyUtilsInstance = new PropertyUtils();
}

private PropertyUtils() {
if (properties == null) {
try {
properties = loadProperties();
} catch (IOException e) {
LOGGER.error("Threw a BadException, full stack trace follows:",e);
e.printStackTrace();
}
}
}

private Properties loadProperties() throws IOException {
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties");
if (inputStream == null) {
throw new FileNotFoundException("not loaded!");
}
properties.load(inputStream);
return properties;
}

public static Properties getProperties() {
return properties;
}

}


we can read the properties in the following way

public static String image_template_path PropertyUtils.getProperties().getProperty("template_card_image_path");
public static String corporateName = PropertyUtils.getProperties().getProperty("corporate_name");
public static String saved_image_path =PropertyUtils.getProperties().getProperty("images_path");


No comments:

Post a Comment