tomcat容器下读取配置文件

  1. 在类中的静态代码块中读取配置文件
    public static String WADDR = "";
    // 226
    public static String ADDR = "";
    public static int EXPIRE_TIME;

static {
        Properties prop = new Properties();

        InputStream in = JedisConfig.class
                .getResourceAsStream("/baseUtil/redis.properties");

        try {
            prop.load(in);
            WADDR = prop.getProperty("redis.host.waddr");
            ADDR = prop.getProperty("redis.host.raddr");
            EXPIRE_TIME = Integer.valueOf(prop.getProperty("EXPIRE_TIME"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2、在tomcat容器下设置一个监听器

@WebListener
public class StartListener implements ServletContextListener{

    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("servlet context 初始化");
        System.out.println(sce.getServletContext().getServerInfo());
        new JedisConfig();// 构造方法
    }

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("servlet context 销毁");
    }

在类中的构造方法中读取配置文件

public class JedisConfig {

    public static String WADDR = "";
    // 226
    public static String ADDR = "";
    public static int EXPIRE_TIME;

    public JedisConfig() {
        Properties prop = new Properties();
        Map map = new HashMap();
        try {
            InputStream resourceAsStream = JedisConfig.class.getClassLoader()
                    .getResourceAsStream("/baseUtil/redis.properties");
            prop.load(resourceAsStream);
            WADDR = prop.getProperty("redis.host.waddr");
            ADDR = prop.getProperty("redis.host.raddr");
            EXPIRE_TIME = Integer.valueOf(prop.getProperty("EXPIRE_TIME"));     
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(tomcat)