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
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