IOC:控制反转,说白了就是把对象的创建、初始化、销毁交给spring容器去完成

DI:依赖注入,即在运行期间有spring容器将依赖关系注入到组件之中(运行期间,由容器根据配置文件,将其他对象的引用通过组件提供的setter或者constructor进行设定)

我觉得IOC和DI的意义就一句话:面向接口编程,减少了模块之间的耦合性。


下面一个小例子来说明这个意义:

Document接口:

public interface Document {
void read();
void write();
}

ExcelDocument实现类:

public class ExcelDocument implements Document {
@Override
public void read() {
System.out.println("read excel");
}
@Override
public void write() {
System.out.println("write excel");
}
}

PdfDocument实现类:

public class PdfDocument implements Document {
@Override
public void read() {
System.out.println("read pdf");
}
@Override
public void write() {
System.out.println("write pdf");
}
}

WordDocument实现类:

public class WordDocument implements Document {
        @Override
        public void read() {
                System.out.println("read word");
        }
        @Override
        public void write() {
                System.out.println("write word");
        }
}


业务类 :

public class DocumentManager {
private Document document;

public DocumentManager(Document document) {
this.document = document;
}

public void read(){
this.document.read();
}

public void write(){
this.document.write();
}
}

配置文件:

<?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="documentManager" class="com.niit.service.DocumentManager">
                <constructor-arg ref="pdfDocument"/>
        </bean>
        <bean id="wordDocument" class="com.niit.service.impl.WordDocument"/>
        <bean id="pdfDocument" class="com.niit.service.impl.PdfDocument"/>
        <bean id="excelDocument" class="com.niit.service.impl.ExcelDocument"/>
</beans>


说明,面向接口编程,我们需要哪一个实现类,即将这个类注入到documentManager这个bean中;


最后在测试类中:

@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DocumentManager manager = (DocumentManager) context.getBean("documentManager");
manager.read();
manager.write();
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐