读取web外的配置文件

一般web项目配置文件都放在classPath下面,读取的时候:

1  import java.io.InputStream;
 2 import java.util.Properties;
 3    public class DealConnection {  
 4           private static String url = "";
 5           private static String user = "";
 6           private static String pwd = "";
 7           private static String connStr="";
 8  //构造方法
 9       public DealConnection() {
10           InputStream istr = DealConnection.class.getClassLoader().getResourceAsStream("/parse.properties");//获取classPath下面的配置文件
11           Properties p=new Properties();
12             p.load(istr);
13             istr.close();
14            //获取各个配置的值
15             url=p.getProperty("url").trim();
16             user=p.getProperty("user").trim();
17             pwd=p.getProperty("pwd").trim();
18             connStr=p.getProperty("connStr");
19    }
20 //数据库连接方法
21     public Connection openConn(){
22         Connection conn=null;
23         try {
24             Class.forName(connStr).newInstance();
25             conn = DriverManager.getConnection(url, user, pwd);
26         } catch (Exception e) {
27             e.printStackTrace();
28         }
29         return conn;
30     } 
31 }

现在如果想把配置文件放到外面,让别人也可以方便修改配置文件,假设:配置文件放到tomcat/bin/conf文件下,就修改读取文件那里

public DealConnection() {
        String name=System.getProperty("user.dir");//得到的路径在tomcat/bin路径
        InputStream istr;
        try {
        istr = new FileInputStream(name + "/conf/parse.properties");//读取就是tomcat/bin/conf下的配置文件
        Properties p=new Properties();
            p.load(istr);
            istr.close();
            url=p.getProperty("url").trim();
            user=p.getProperty("user").trim();
            pwd=p.getProperty("pwd").trim();
            connStr=p.getProperty("connStr");
        } catch (Exception e) {
            e.printStackTrace();
        }

applicationContext.xml,在读取classPath配置文件的时候,路径classpath:jdbc.properties

<!-- 属性文件的位置 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:jdbc.properties</value>
        </property>
    </bean>

 如果要读取tomcat/bin/conf下的配置文件,路径改成:file:conf/jdbc.properties,它是相对于web容器的

<!-- 属性文件的位置 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:conf/jdbc.properties</value>
        </property>
    </bean>

 

转载于:https://www.cnblogs.com/junrong624/p/4914050.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值