spring-framework-3.2.4.RELEASEjava
jdk1.7.0_11spring
Maven3.0.5eclipse
eclipse-jee-juno-SR2-win32this
此例沒必要重複建立項目,上接Spring3-Example項目。spa
與前一個項目Spring3-Example中的pom.xml文件一致,沒必要修改。code
假設你的項目須要輸出到CVS或者JSON,建立如下類。xml
文件1:IOutputGenerator.java 一個output接口blog
package com.lei.demo.loosely_coupled; public interface IOutputGenerator { public void generateOutput(); }
文件2:CsvOutputGenerator.java CVS輸出,實現了IOutputGenerator接口接口
package com.lei.demo.loosely_coupled; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput() { System.out.println("輸出CsvOutputGenerator生成 Output......"); } }
文件3:JsonOutputGenerator.java JSON輸出,實現了IOutputGenerator接口ip
package com.lei.demo.loosely_coupled; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput() { System.out.println("輸出JsonOutputGenerator生成 Output......"); } }
用Spring的鬆耦合實現輸出相應的格式。
首先建立一個須要用到輸出的類OutputHelper.java
package com.lei.demo.loosely_coupled; public class OutputHelper { IOutputGenerator outputGenerator; public void generateOutput(){ this.outputGenerator.generateOutput(); } public void setOutputGenerator(IOutputGenerator outputGenerator){ this.outputGenerator = outputGenerator; } }
src/main/resources下建立配置文件Spring-Output.xml。
<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-3.0.xsd"> <bean id="OutputHelper" class="com.lei.demo.loosely_coupled.OutputHelper"> <property name="outputGenerator" ref="CsvOutputGenerator" /> </bean> <bean id="CsvOutputGenerator" class="com.lei.demo.loosely_coupled.CsvOutputGenerator" /> <bean id="JsonOutputGenerator" class="com.lei.demo.loosely_coupled.JsonOutputGenerator" /> </beans>
App.java類
package com.lei.demo.loosely_coupled; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { private static ApplicationContext context; public static void main(String[] args){ context = new ClassPathXmlApplicationContext(new String[] {"Spring-Output.xml"}); OutputHelper output = (OutputHelper)context.getBean("OutputHelper"); output.generateOutput(); } }
如今,已經實現了鬆耦合,當須要輸出改變時,沒必要修改任何代碼.java文件,只要修改Spring-Output.xml文件<property name="outputGenerator" ref="CsvOutputGenerator" />中的ref值,就能夠實現輸出不一樣的內容,不修改代碼就減小了出錯的可能性。
運行以上App.java,「輸出CsvOutputGenerator生成 Output......」,結果以下圖