package main.java.com.mycompany.service;
public interface IOutputGenerator {
public void generateOutput();
}package main.java.com.mycompany.service.impl;
import main.java.com.mycompany.service.IOutputGenerator;
public class CsvOutputGenerator implements IOutputGenerator {
@Override
public void generateOutput() {
System.out.println("Csv Output Generator");
}
}package main.java.com.mycompany.service.impl;
import main.java.com.mycompany.service.IOutputGenerator;
public class JsonOutputGenerator implements IOutputGenerator{
@Override
public void generateOutput() {
System.out.println("Json Output Generator");
}
}package main.java.com.mycompany.util;
import main.java.com.mycompany.service.IOutputGenerator;
public class OutputHelper {
IOutputGenerator outputGenerator;
public void generateOutput(){
outputGenerator.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
}
}<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="main.java.com.mycompany.util.OutputHelper"> <property name="outputGenerator" ref="CsvOutputGenerator"></property> </bean> <bean id="CsvOutputGenerator" class="main.java.com.mycompany.service.impl.CsvOutputGenerator"> </bean> <bean id="JsonOutputGenerator" class="main.java.com.mycompany.service.impl.JsonOutputGenerator"> </bean> </beans>
package main.java.com.mycompany.util;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class OutputHelperTest {
@Test
public void outputHelperTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
OutputHelper output = (OutputHelper) context.getBean("OutputHelper");
output.generateOutput();
}
}<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="main.java.com.mycompany.util.OutputHelper"> <property name="outputGenerator" ref="JsonOutputGenerator"></property> </bean> <bean id="CsvOutputGenerator" class="main.java.com.mycompany.service.impl.CsvOutputGenerator"> </bean> <bean id="JsonOutputGenerator" class="main.java.com.mycompany.service.impl.JsonOutputGenerator"> </bean> </beans>
本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1908705
原文地址:http://suyanzhu.blog.51cto.com/8050189/1908705