一、创建一个Web项目,导入jar包到lib目录下
(1)导包 : 4个核心(beans、core、context、expression) + 1个依赖(commons-loggins.jar)
(2)编写配置文件: applicationContext.xml 放在src资源目录下
<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">
<!-- 实例化对象: 交给spring的ioc容器去管理 -->
<bean id="userService" class="com.qf.service.impl.UserServceImpl"></bean>
<!-- <bean id="userService2" class="com.qf.service.impl.UserServceImpl2"></bean> -->
</beans>
(3)建立测试类
3.1 获取ApplicationContext对象:
ApplicationContext context = new ClassXmlPathApplicationContext(“配置文件”);
3.2 获取bean对象,转成IUserService对象
IUserService userService = context.getBeans(“userService”);
3.3 调用方法
userService.add();
public class IOCTest {
//面向接口编程:
//private IUserService userService = new UserServceImpl();
@Test
public void iocTest(){
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
//1.通过id拿到配置文件中的bean对象
//IUserService userService = (IUserService) context.getBean("userService");
//2.通过类型去获取bean对象
IUserService userService = context.getBean(IUserService.class);
userService.add();
}
}
service接口和实现类
public interface IUserService {
public void add();
}
public class UserServceImpl implements IUserService {
@Override
public void add() {
System.out.println("userService add...");
}
}