1、新建Java项目导入依赖jar包,参考前一章
2、以不同文件格式输出为例
3、定义接口IOutputGenerator.java
package com.spring.output;public interface IOutputGenerator { public void generateOutput();}4、CsvOutputGenerator和JsonOutputGenerator类,分别实现接口
CsvOutputGenerator.java
package com.spring.output;public class CsvOutputGenerator implements IOutputGenerator{ @Override public void generateOutput() { // TODO Auto-generated method stub System.out.println("CSV output Generator"); }}JsonOutputGenerator.java
package com.spring.output;public class JsonOutputGenerator implements IOutputGenerator{ @Override public void generateOutput() { // TODO Auto-generated method stub System.out.println("Json output Generator"); }}5、编写辅助类,通过setter注入
OutputHelper.java
package com.spring.output;public class OutputHelper { IOutputGenerator outputGenerator; public void generateOutput(){ outputGenerator.generateOutput(); } public void setOutputGenerator(IOutputGenerator outputGenerator) { this.outputGenerator = outputGenerator; }}6、编辑beans.xml:
7、测试:
package com.spring.output;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext content = new ClassPathXmlApplicationContext("beans.xml"); OutputHelper outputHelper = (OutputHelper) content.getBean("OutputHelper"); outputHelper.generateOutput(); }}8、可修改beans.xml中的ref的值
9、运行结果
Json output Generator