【工程截图】
【Document.java】
package com.HigginCui.document.annotation; public interface Document { public void readDocument(); public void writeDocument(); }
【ExcelDocument.java】
package com.HigginCui.document.annotation; import org.springframework.stereotype.Component; @Component("excelDocument") public class ExcelDocument implements Document{ @Override public void readDocument() { System.out.println("Excel read...."); } @Override public void writeDocument() { System.out.println("Excel write...."); } }
【PdfDocument.java】
package com.HigginCui.document.annotation; import org.springframework.stereotype.Component; @Component("pdfDocument") public class PdfDocument implements Document{ @Override public void readDocument() { System.out.println("Pdf read...."); } @Override public void writeDocument() { System.out.println("Pdf write...."); } }
【WordDocument.java】
package com.HigginCui.document.annotation; import org.springframework.stereotype.Component; @Component("wordDocument") public class WordDocument implements Document{ @Override public void readDocument() { System.out.println("Word read...."); } @Override public void writeDocument() { System.out.println("Word write...."); } }
【DocumentManager.java】
package com.HigginCui.document.annotation; import javax.annotation.Resource; import org.springframework.stereotype.Component; @Component("documentManager") public class DocumentManager { @Resource(name="excelDocument") private Document document; public void read(){ this.document.readDocument(); } public void write(){ this.document.writeDocument(); } }
【applicationContext.xml】
<?xml version= "1.0" encoding ="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- 把一个类放入到Spring容器中,该类就是一个component,此时不需要声明对应的bean --> <context:component-scan base-package="com.HigginCui.document.annotation"></context:component-scan> </beans>
【testDocument.java】
package com.HigginCui.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.HigginCui.document.annotation.DocumentManager; public class testDocument { @Test public void test(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); DocumentManager documentManager=(DocumentManager) context.getBean("documentManager"); documentManager.write(); documentManager.read(); } }
【运行结果】
Excel write....
Excel read....