package com.yiibai.output; public interface IOutputGenerator { public void generateOutput(); }
package com.yiibai.output.impl; import com.yiibai.output.IOutputGenerator; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput() { System.out.println("This is Csv Output Generator"); } }
package com.yiibai.output; import com.yiibai.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.yiibai.output.OutputHelper"> <property name="outputGenerator" ref="CsvOutputGenerator" /> </bean> <bean id="CsvOutputGenerator" class="com.yiibai.output.impl.CsvOutputGenerator" /> </beans>
package com.tw511.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.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