学习spring不久,分享一个简单的spring程序,创建一个简单的PoJo,HelloWorld.java
package common.test; public class HelloWorld{ private String msg; public String getMsg(){ return msg; } public void setMsg(String msg){ this.msg = msg; } }
创建一个配置文件config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--定义一个bean--> <bean id="HelloWorld" class="common.test.HelloWorld"> <!--将其变量msg通过依赖注入--> <property name="msg"> <value>HelloWorld</value> </property> </bean> </beans>
创建TestHelloWorld.java
package common.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class TestHelloWorld{ public static void main(String args[]){ //通过spring的ApplicationContext来获取spring的配置文件 ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml"); //通过Bean的id来获取Bean HelloWorld hw=(HelloWorld)actx.getBean("HelloWorld"); System.out.println(hw.getMsg()); } }
输出结果:HelloWorld
上面是通过使用FileSystemXmlApplicationContext的方式获取配置文件的
其实还可以使用ClassPath方式获取配置文件并加载这些文件,创建上下文
应用中最多的是在web.xml中添加一个listener并配置spring的listener类来加载上下文的。
而spring 代码中 明确写明了 默认会加载的文件名称是applicationContext.xml自然在web.xml中就不用配置这个属性了。