package com.zyiz.output; public interface IOutputGenerator { public void generateOutput(); }
package com.zyiz.output.impl; import com.zyiz.output.IOutputGenerator; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput() { System.out.println("This is Csv Output Generator"); } }
package com.zyiz.output; import com.zyiz.output.IOutputGenerator; public class OutputHelper { IOutputGenerator outputGenerator; public void generateOutput() { outputGenerator.generateOutput(); } //DI via setter method public void setOutputGenerator(IOutputGenerator outputGenerator) { this.outputGenerator = outputGenerator; } }
在这种情况下,Spring将通过setter方法注入Bean “CsvOutputGenerator” 到“OutputHelper”类,“setOutputGenerator(IOutputGenerator 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-2.5.xsd"> <bean id="OutputHelper" class="com.zyiz.output.OutputHelper"> <property name="outputGenerator" ref="CsvOutputGenerator" /> </bean> <bean id="CsvOutputGenerator" class="com.zyiz.output.impl.CsvOutputGenerator" /> </beans>
package com.zyiz.netmon; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zyiz.output.OutputHelper; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); OutputHelper output = (OutputHelper)context.getBean("OutputHelper"); output.generateOutput(); } }
输出结果
This is Csv Output Generator