1.1在src中添加两个包com.huizhi.hello和com.huizhi.test
1.2在com.huizhi.hello中新建一个Class文件。
package com.huizhi.hello; public class hello { private String name; public void setName(String name) { this.name = name; } public String say() { return "hello :" + name ; } }
1.3在com.huizhi.test中新建一个Class文件。然后运行测试是否能够打印内容到控制台。
package com.huizhi.test; import com.huizhi.hello.hello; public class test { public static void main(String[] args) { hello h1 = new hello(); h1.setName("张三"); System.out.println(h1.say()); } }
2、把Spring的jar包拷贝到项目中。
3、在src目录下新建一个XML配置文件applicationContext.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 id="helloWorld" class="com.huizhi.hello.hello"> <property name="name" value="李四"/> </bean> </beans>
4、回到com.huizhi.test.test.java文件,把原来的测试实例注释掉。加入新的测试方法。运行测试,查看控制台的输出内容
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); hello h1 = (hello) appContext.getBean("helloWorld"); System.out.println(h1.say());