测试spring的搭建
案例:
PersonService.java:
package blog.service; public interface PersonService { public abstract void save(); }
PersonServiceBean.java:
package blog.service.impl; import blog.service.PersonService; public class PersonServiceBean implements PersonService { public void save(){ System.out.println("in save method!"); } }
beans.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"> <!-- id属于xml所有的属性,是确定bean唯一的属性,不能包含特殊字符 建议第一个字母小写 --> <!-- name属性可以包含特殊字符,当不包含特殊字符时应选用id来表示bean,id可以被xml解析 --> <bean class="blog.service.impl.PersonServiceBean" id="personService"></bean> </beans>
springtest.java:
package junit.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import blog.service.PersonService; import blog.service.impl.PersonServiceBean; public class springtest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring(){//实例化spring容器 //使用:在类路径寻找配置文件来实例化容器 ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"}); PersonService personService = (PersonServiceBean)ctx.getBean("personService"); personService.save(); } }