1.从文件系统中读(配置文件位置随意指定)
Properties p = new Properties();
p.load(new FileInputStream("D://Mycode//pro.properties"));
String es_node = p.getProperty("es.node");
2.从类路径的resources下读
ResourceBundle bundle = ResourceBundle.getBundle("config");
String url = bundle.getString("url");
该方法默认读取的是resources文件夹下的以.properties为后缀的文件,代码中的例子即为config.properties
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));
3.读取xml文件
1).利用ClassPathXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");
HelloBean helloBean = (HelloBean)context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
2).利用FileSystemResource读取
Resource rs = new FileSystemResource("D:/software/beanConfig.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");\
System.out.println(helloBean.getHelloWorld());
网友评论