读取配置的方式

1、ResourceBundle.getBundle,配置文件得放在 WEB-INF\class 目录下

package com.seam.mango.action.config;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.log.Log;

import com.seam.mango.action.home.ActionHome;

@Scope(ScopeType.APPLICATION)
@Startup(depends = "systemConfigAction")
@Name("appMessageAction")
public class AppMessageAction extends ActionHome {

    private static final long serialVersionUID = -3238871819741809897L;

    @Logger
    private Log log;

    private ResourceBundle resourceBundle;

    @Create
    public ResourceBundle loadBundle() {

        String bundleName = "mango-app";
        try {
            resourceBundle = ResourceBundle.getBundle(bundleName);
        } catch (MissingResourceException mre) {
            log.error("resource bundle missing: " + bundleName);
            return null;
        }
        return resourceBundle;
    }

    public String getMessage(String key) {
        String value = "";
        
        try {
            value = resourceBundle.getString(key);
        } catch (Exception e) {
            value = key;
        }
        
        return value;
    }
}

2、getResourceAsStream,配置文件放在package里,但是ant的build.xml配置文件得让配置文件也能写到war包中,否则只有class文件能被写到war包中

package com.Socket.util;

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

import com.Socket.event.FrequencyProperty;

public final class PropertiesUtil {

    private static Properties prop;

    static {
        prop = new Properties();
        try {
            InputStream in = PropertiesUtil.class.getResourceAsStream("com.Socket/dzxh.properties");
            prop.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getPropertity(String key) {
        return prop.getProperty(key);
    }
    
//    public static void main(String[] args) {
//        System.out.println(PropertiesUtil.getPropertity("jxt.db.userName"));
//        System.out.println(PropertiesUtil.getPropertity("yxt.db.host"));
//    }

}

如下图所示,配置文件并未写到war包中

 

 

 

 

 

 

 

 

 3、在jar包里看到的,用的也是getResourceAsStream

 

 

 

 

 4、

package com.Socket.event;

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

public class PropertyMgr {
    private static Properties props = new Properties();
    
    static {
        try {
            props.load(PropertyMgr.class.getClassLoader().getResourceAsStream("hot/com/Socket/event/config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getProperty(String key) {
        return props.getProperty(key);
    }
}

 

posted @ 2020-12-01 17:34  1156740846  阅读(165)  评论(0编辑  收藏  举报