spring 下得到properties中的配置文件

本文介绍了一个Java程序中用于加载和更新配置文件的方法。通过使用Properties类,可以在运行时读取配置并允许对其进行修改。此外,还展示了如何利用Spring框架从类路径下加载配置文件。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class SystemConfig {
private static Properties props = new Properties(); 

static{
try {
props.load(getLocation().getInputStream());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getValue(String key){
return props.getProperty(key);
}
    public static void updateProperties(String key,String value) {    
         props.setProperty(key, value); 
    }
    
    /*
     * getServerName
     * 获取当前服务器运行环境的名称,用来标示是在运行环境中的哪台服务器
     */
    public static String getServerName(){
   
    String serverName = getValue("server_name");
    if(null!=serverName)
    return serverName;
    else
    return "Unknown Server";
    }
    
public static Resource getLocation() {
Resource location =null;
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{});
if(null==location){
location = context.getResource("classpath:PhotoConfig.properties");
}
return location;
}

public static Resource getResource(String fileName) {
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{});
return context.getResource("classpath:"+fileName);
}

public static void main(String[] args) {
System.out.println(SystemConfig.getValue("server_name"));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值