【1】创建beans.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-2.5.xsd"> <bean id="personService" class="com.bird.service.impl.PersonServerImpl"></bean> </beans>
【2】JavaBean编写
package com.bird.service; public interface PersonServer{ void save(); } package com.bird.service.impl; import com.bird.service.PersonServer; public class PersonServerImpl implements PersonServer{ public void save() { System.out.println("HelloWord!"); } }
【3】Test测试
package com.bird.service.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bird.service.PersonServer; public class TestSpring { public static void main(String []args){ //初始化 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //用getBean方法调用personService对象 PersonServer s = (PersonServer)ctx.getBean("personService"); //调用save方法 s.save(); } }
【4】测试结果如下
2013-5-9 11:20:54 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7: startup date [Thu May 09 11:20:54 CST 2013]; root of context hierarchy
2013-5-9 11:20:54 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
2013-5-9 11:20:54 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1ce2dd4: defining beans [personService]; root of factory hierarchy
HelloWord!