Spring IOC是什么?
IOC-控制反转,不是一种技术,而是一种设计思想。
为什么使用Spring IOC?
让专业的人去做专业的事情,只要保留接口给别人调用就行了,而当你调用别人的接口时,你不需要知道内部逻辑,你只要了解别人的接口有哪些功能就行了。
使用Spring IOC的步骤
1.做一杯果汁
public class Source { private String fruit;//类型 private String sugar;//糖分描述 private String size;//大小杯 //getter setter }
2.果汁送到店里去
public class JuiceMaker { private String beverageShop=null; private Source source=null; //getter setter public String makeJuice() { String juice="这是一杯由"+beverageShop+"饮品店,提供的"+source.getSize()+source.getSugar()+source.getFruit(); return juice; } }
3.我要在贡茶店里买一杯大杯少糖橙汁
对方现在配置:
<?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-4.0.xsd"> <bean id="source" class="test3.Source"> <property name="fruit" value="橙汁"/> <property name="sugar" value="少糖"/> <property name="size" value="大杯"/> </bean> <bean id="juiceMaker" class="test3.JuiceMaker"> <property name="beverageShop" value="贡茶"/> <property name="source" ref="source"/> </bean> </beans>
我得到了:
public class Test { //对于我来说我只是想要一杯果汁,我直接找贡茶饮品店去买,而贡茶饮品店是怎么制作的我不关心 //对于饮品店来说,它提供店面,找别人外包商提供果汁就行了,外包商专业做果汁的,他就能很专业的做好果汁 public static void main(String[] args) { //配置文件跟包是并列的 ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("spring-cfg.xml"); JuiceMaker juiceMaker =(JuiceMaker)ctx.getBean("juiceMaker"); System.out.println(juiceMaker.makeJuice()); } }