重点掌握控制反转的操作意义
控制反转IOC(Inversion Of Control)
是一种包转技术类型:所有对象实例化的处理操作都不需要关键字new(反射机制)。
传统方式
incterface Fruit {
public void eat();
}
class Apple implements Fruit {
public void eat(){
System.out.println("*** 吃苹果");
}
}
public class TestDemoA{
public static void main(String[] args) {
Fruit f = new Apple();
f.eat();
}
}
这样写耦合度加深,因为某一个接口必须与一个子类产生关联。
工厂模式
incterface Fruit {
public void eat();
}
class Apple implements Fruit {
public void eat(){
System.out.println("*** 吃苹果");
}
}
class Fuctory {
public static Fruit getFruit() {
return new Apple();
}
}
public class TestDemoA{
public static void main(String[] args) {
Fruit f = Factory.getFruit() ;
f.eat();
}
}
加入工厂设计之后最大的优点在在于,整个的代码在操作的过程之中,只会与工厂类发生耦合,这个工厂需要开发者明确的使用
Spring模式
public class testApple {
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
apple app = cxt.getBean("eatApple",eatApple.class);
app.eat();
}
}
public interface apple {
public void eat();
}
public class eatApple implements apple {
public void eat(){
System.out.println("吃苹果");
}
}
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">
<bean id="eatApple" class="cn.edu.main.eatApple"/>
</beans>
整个代码操作过程中无法发现工厂模式的明确使用,因为所有的工厂都由 Spring帮助用户自动处理,且在applicationContext.xml文件配置的信息内容,都在Spring容器启动的时候默认的实例化好了所有的对象,用的时候根据id名称取出即可。
在编写的代码过程中也是用到几个类
1.ApplicationContext类(org.springframework.context.ApplicationContext;)
所有在applicationContext.xml文件中配置的信息都需要通过此类读取才可使用。
常用方法:public<T>T getBean(String name,Class<T>require)
取得只等名称的Bean对象,并且设置泛型为制定操作的Bean类型,避免向下转型。
2.现在由于资源控制文件可能在任意的位置上,例如:CLASSPATH中或者在磁盘文件中,那么就必须使用相关的子类:org.springframework.context.support.ClassPathXmlApplicationContext;(在CLASSPASS中读取资源文件)
所有在Spring中配置的<bean>元素都表示在Spring容器启动的时候自动完成实例化。
总结
Spring是一个非常庞大的工厂,所有的对象实例化等辅助部分不再需要由用户自己负责处理,全部交给Spring完成,用户只需要根据自己的需求饮用对象实例即可。
网友评论