Spring
IOC ( 控制反转 Inverse of Controller)
Spring中对象工厂(Spring容器):
对象不能自己通过new 来创建,而是要通过Spring容器来创建(对象工厂),所以对象的创建的权利发生了反转,反转给容器创建. A类和B类对象都交给容器创建,在A类中定义一个B类的属性,可以通过属性的set方法给属性赋值.
解耦合:对象由容器创建,管理,耦合关系解除
容器默认是通过反射来创建bean 对象:
Class c1 = Class.forName(全类名);
Class c2 = 类名.class
Class c3 = 对象.getClass();
框架底层创建对象原理 :反射动态创建对象
输入类名 创建对象
Scanner sca = new Scanner (System.in)
String className =sca.next();
Class c = Class.forName(className);
Object obj = c. newInstance();
导入jar包
commons-logging-1.1.1.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
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-3.1.xsd">
<!--将dao对象 和service对象交给容器统一创建
class :全类名,不能写接口
id: 唯一标识
lazy-init: 延迟创建对象 true 在调用方法时延迟创建 false 在创建容器时立即创建
scope: singleton: 单例的 只创建一个对象 prototype: 多例的,调用一个创建一个
request: web 环境下 一次请求创建一个对象
session: web 环境下 一次会话创建一个对象
init-method: 指定初始化方法(值为方法名) 容器创建时会调用
destroy-method: 容器销毁时创建
-->
<bean class="dao.DeptDaoHibernateImpl" destroy-method="destroy" init-method="init" scope="singleton" lazy-init="true" id="deptDao">相当于new 了一个对象
</bean>
<bean class="dao.DeptDaoJDBCImpl" id="deptDao2">
</bean>
<bean class="dao.DeptDaoMybatisImpl" id="deptDao3">
</bean>
<bean class="service.DeptServiceImpl" id="deptService">
<!-- name:属性名 ref : bean的id值
底层会调用dao属性 set方法
-->
<property name="dao" ref="dept"></property> 给属性赋值, 更换id值可以更换调用的dao
</beans>
测试
创建容器对象 加载applicationContext.xml ,创建bean对象*(调用的构造方法)
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 创建工厂耗时较多, 在框架整中通过监听器来创建
获取bean对象
IDeptService service = (IDeptService) ac .getBean("deptService");
service.saveDepte(new Dept()); // 调用Dao的方法