springIOC和DI的意义
2016-04-26 14:26
447 查看
springIOC和DI的意义:
实现了完全的面向接口编程document案例MVC案例 Document案例-使用构造方法的依赖注入接口
public interface Document { void read(); void write(); }实现类1
public class WordDocument implements Document { public void read() { System.out.println("word read"); } public void write() { System.out.println("word writer"); } }实现类2
public class PDFDocument implements Document { public void read() { System.out.println("pdf read"); } public void write() { System.out.println("pdf write"); } }
工具类
public class DocumentManager { public Document document; public DocumentManager(Document document){ this.document = document; } public void read(){ document.read(); } public void write(){ document.write(); } }测试
public class Test1 { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DocumentManager manager = (DocumentManager) context.getBean("DocumentManager"); manager.read(); manager.write(); } }spring配置文件applicationContext.xml
<bean id="DocumentManager" class="spring_ioc_di_document.DocumentManager"> <constructor-arg index="0" ref="pdfDocument"></constructor-arg></bean> <bean id="wordDocument" class="spring_ioc_di_document.WordDocument"></bean> <bean id="pdfDocument" class="spring_ioc_di_document.PDFDocument"></bean>mvc案例-使用set方式依赖注入dao接口
public interface PersonDao { public void read(); }dao实现
public class PersonDaoImpl implements PersonDao { public void read() { System.out.println("personDao read"); } }service接口
public interface PersonService { public void read(); }
service实现
public class PersonServiceImpl implements PersonService{ PersonDao persondao; public PersonDao getPersondao() { return persondao; } public void setPersondao(PersonDao persondao) { this.persondao = persondao; } @Override public void read() { persondao.read(); } }测试
public class Test2 { @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonAction action = (PersonAction) context.getBean("PersonAction"); action.read(); } }spring配置文件applicationContext.xml
<bean id="personDao" class="spring_mvc.PersonDaoImpl"></bean> <bean id="personService" class="spring_mvc.PersonServiceImpl" > <property name="persondao" > <ref bean="personDao"/> </property> <bean id="PersonAction" class="spring_mvc.PersonAction"> <property name="service"> <ref bean="personService"/> </property> </bean>
相关文章推荐
- java程序打包成jar 配置文件信息路径
- SpringMVC—相关注解介绍
- java中list,set,map的区别
- 基于优先级队列java线程池
- 输出n对括号所有有效的匹配 java实现
- 关于博主
- 深入学习Java虚拟机(三)
- spring4整合Hibernate4过程中遇到的事物管理问题
- Java SpringMVC项目导入excel2003以及2007多版本自动识别对应工具类(util)
- Spring Boot 之 HelloWorld详解
- Spring Boot 之 HelloWorld详解
- 趣味分数-三个数的最小公倍数-java
- Spring与Quartz的整合实现定时任务调度
- Java 类型转换
- leetcode 206 ---Reverse Linked List 链表 反转
- 【JavaEE框架】MyBatis基础使用
- 在导入eclipse项目到Android Studio出现这样的错误, 非法字符: '\ufeff' 解决方案|错误: 需要class, interface或enum,查阅后了解到Eclipse可以智
- java主键生成
- AES加密算法,JAVA实现示例
- java源码分析(2)-String(1)