1.下载Spring jar包,并添加到项目中。
官网地址http:springsource.org
2.在项目中新建一个类
package cn.test;public class HelloSpring {// 定义属性,该属性的值将通过Spring框架进行设置private String result;/** * 定义一个打印的方法用于输出result的值 */public void print() {System.out.println("Hello" + getResult() + "!"); }public HelloSpring() {super();// TODO Auto-generated constructor stub}public String getResult() {return result;}public void setResult(String result) {this.result = result;}}
3.编写Spring配置文件,在src目录下创建applicationContext.xml文件配置如下
Heyongjun
4.书写测试类
package cn.test; import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { //通过ClassPathXmlApplicationcontext实例化Spring的上下文 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //通过Applicationcontext中的getBean()方法,根据id来获取Bean实例 HelloSpring hs= (HelloSpring)context.getBean("hellpSpring"); hs.print(); }}