一.IOC概念及原理
1)IOC:控制反转,即就是对象的创建不是通过new方式,而是交给spring配置创建。
2)IOC底层原理:
使用的技术:xml配置文件,dom4j解析,工厂设计模式,反射
a)最开始我们创建类是通过new一个,但是这种方式耦合度太高,如果其他类中使用了这个类,这个类的名字如果发生改变,其他类中也要相应的进行改变。
b)出现了工厂设计模式解耦合,比如:service调用dao
public class Dao{
public void test(){
...
}
}
public class Service{
Dao dao = Factory.getDao();
...
}
public class Factory{
public static Dao getDao(){
return new Dao();
}
}
这里又出现了新的耦合度:service和factory
c)下来是IOC的解耦合底层原理:
public class Dao{
public void test(){
...
}
}
public class Service{
Dao dao = Factory.getDao();
...
}
第一步:创建xml配置文件:
<bean id="dao" class="com.dao.DAO"/>
第二步:创建工厂类,使用dom4j解析xml文件,使用反射创建类
public class Factory{
public static Dao getDao(){
1.使用dom4j解析xml文件,获取class的值
String str = class的值;
2.使用反射创建对象
Class c = Class.forName(str);
Dao dao = c.newInstance();
return dao;
}
}
这里即使dao的名字或者包名发生了改变,调用的类中相关代码也不用改变,降低了耦合度
二.IOC的使用
1.导入jar包
导入这些核心包,再加上日志相关包
2.创建类
3创建配置文件,配置文件名不固定,建议是applicationContext.xml
1)在该文件中要先引入schema约束
2)配置对象创建
使用bean标签,bean标签属性a)id:名字b)class:类的全路径c)name:与id类似,区别是name中可以有特殊符号d)scope:一般用singleton(单例),prototype(多例)不写默认是singleton
4写测试类
如:
创建类:
public class MyTestBean {
public void test()
{
System.out.println("test...");
}
}
applicationContext.xml,一般放在src下面
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="myTestBean" class="main.java.MyTestBean"></bean>
</beans>
测试类:
public class beanTest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyTestBean bean =(MyTestBean) context.getBean("myTestBean");
bean.test();
}
}
运行结果: