java web 44 : Spring
src/main/resources 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.xsd"> <!-- 将EmpService接口的实现类作为bean注册到spring容器中, 即让spring容器创建该类的实例 。 如果注册的类有父接口,id值通常是接口名(首字母小写) 如果注册的类没有父接口,id值通常为类名(首字母小写)--> <bean id="empService" class="com.tedu.service.EmpServiceImpl"></bean> </beans>
com.tedu.service/EmpService.java(接口)
package com.tedu.service; /** 模拟员工模块的service层接口 **/ public interface EmpService { //新增员工信息 public void add(); }
com.tedu.service/EmpServiceImpl.java
package com.tedu.service; /** 模拟员工模块的servic接口的实现类(子类)*/ public class EmpServiceImpl implements EmpService { @Override public void add() { System.out.println("EmpServiceImpl...add()..."); } }
com.tedu/TestService.java
package com.tedu; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tedu.service.EmpService; import com.tedu.service.EmpServiceImpl; public class TestService { @Test public void testService() { //创建Spring的容器对象 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过spring容器获取EmpService接口的子类实例 EmpService service = (EmpService) ac.getBean("empService"); service.add(); } }
Run As Junit Test: