标签:spring
一般写程序时我们都会将一些配置信息写到配置文件中,以便在不修改源码的情况下对程序的某些点进行更改。这里介绍一种Spring读取xml配置文件的方式,其基本思路如下:定义一个java类,其中定义一些静态变量对应我们的配置信息,然后采用注入的方式将变量值初始化为配置值。示例代码如下:
新建一个java类:
package java; public class Config { //要配置的值 public static int value = 0; //这里不能写成静态的 public void setValue(int i) { value = i; } }新建一个config.xml文件,放置我们的配置信息
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <bean class="java.Config"> <!-- 配置信息 --> <property name="value"> <value>5</value> </property> </bean> </beans>然后在applicationContext.xml引入config.xml
<import resource="config.xml"/>ok,下面测试一下我们的程序
public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(Config.value); }输出结果为5
我们在使用ssh集成开发时也可以使用这种方式,而且调用比较方便,因为变量是静态的,直接通过类名就可以调用。
标签:spring
原文地址:http://blog.csdn.net/zhangjk1993/article/details/39937793