导入jar包
4+1 : 4个核心(beans, core , context , expression) + 1个依赖(commons-loggins.jar)
目标类
提供UserService接口和实现类
package com.itheima.a_ioc;
public interface UserService {
public void addUser() ;
}
package com.itheima.a_ioc;
public class UserServiceImpl implements UserService{
// @Override
public void addUser(){
System.out.println("a_Ioc add user");
}
}
获得UserService实现类的实例(从Spring工厂获得,需要将实现类的全限定名称配置到xml文件)
配置文件
位置:任意, 开发中一般在classpath下(src)
名称:任意, 开发中常用 applicationContext.xml
内容: 添加Schema约束 + 配置Service
<?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">
<!-- bean definitions here -->
<bean id = "UserServiceImplId" class = "com.itheima.a_ioc.UserServiceImpl" ></bean>
</beans>
测试
获得容器+ 获得内容
package com.itheima.a_ioc;
import org.apache.catalina.core.ApplicationContext;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
@Test
public void demo02(){
String xmlPath = "com/itheima/a_ioc/beans.xml" ;
ClassPathXmlApplicationContext a = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) a.getBean("UserServiceImplId") ;
userService.addUser();
}
}