JAVAWEB系统启动时,初始化配置文件信息

来源:互联网 发布:网络黄金 未来城app 编辑:程序博客网 时间:2024/06/15 09:42

第一步写Properties工具类,如下:

import java.util.Properties;public class PropertiesUtil {private static Properties jdbc = new Properties();private static Properties system = new Properties();private PropertiesUtil() {}public static Properties getJdbc() {return jdbc;}public static void setJdbc(Properties jdbc) {PropertiesUtil.jdbc = jdbc;}public static Properties getSystem() {return system;}public static void setSystem(Properties system) {PropertiesUtil.system = system;}public static String getJdbcProperty(String key) {return jdbc.getProperty(key);}public static String getJdbcProperty(String key, String defaultValue) {String value = jdbc.getProperty(key);if (value == null || value.trim().isEmpty()) {return defaultValue;}return value;}public static String getSystemProperty(String key) {return system.getProperty(key);}public static String getSystemProperty(String key, String defaultValue) {String value = system.getProperty(key);if (value == null || value.trim().isEmpty()) {return defaultValue;}return value;}}


第二步,写启动监听器如下:

import java.io.IOException;import java.io.InputStream;import java.util.Properties;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jeecms.cms.webservices.util.PropertiesUtil;/** * 系统启动时加载配置文件信息 *  * @author 罗勇 *  * @date 2014-4-2 */public class InitSystemListener implements ServletContextListener {    private static final Logger LOG = LoggerFactory.getLogger(InitSystemListener.class);    public void contextInitialized(ServletContextEvent servletContextEvent) {        this.initSystem();    }    /**     * 初始化配置文件信息     */    private void initSystem() {        // 加载配置文件        PropertiesUtil.setJdbc(getProperties("jdbc.properties"));        PropertiesUtil.setSystem(getProperties("system.properties"));    }    private Properties getProperties(String propertiesName) {        Properties props = new Properties();        InputStream is = null;        try {            is = getClass().getResourceAsStream("/../config/" + propertiesName);            props.load(is);            LOG.info("初始化配置文件" + propertiesName);        } catch (IOException e) {            LOG.error("初始化配置文件" + propertiesName + "出现异常", e);        } finally {            try {                if (is != null)                    is.close();            } catch (IOException e) {                LOG.error("初始化配置文件,关闭is流出现异常", e);            }        }        return props;    }    public void contextDestroyed(ServletContextEvent servletContextEvent) {    }}



第三部,在web.xml中添加如下配置:

        <listener>
<listener-class>com.jeecms.cms.service.InitSystemListener</listener-class>
</listener>

0 0
原创粉丝点击