什么是IOC?
它是Inverse of Control,控制反转,将对象的创建权力反转给Spring框架!!
Spring核心容器需要四个jar包
同时还需要与日志相关的两个jar包,从spring-framework-3.0.2.RELEASE-dependencies中寻找
复制log4j.properties到src下:
代码:
创建一个接口
package com.icbc.spring.study1;
public interface UserDao {
public void save();
}
2.创建一个实现类
package com.icbc.spring.study1;
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("用户保存...");
}
}
3 创建Spring的核心配置文件
在src下新建Spring核心配置文件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">
</beans>
配置UserDaoImpl类
<?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 id="userDao" class="com.icbc.spring.study1.UserDaoImpl"></bean>
</beans>
5.编写测试类
package com.icbc.spring.study1;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void test1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
userDao.save();
}
}
我们可以从spring容器中获取对象。