标签:spring
实现了完全的面向接口编程
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>
标签:spring
原文地址:http://8477424.blog.51cto.com/8467424/1767855