package com.yiibai.output; public interface IOutputGenerator { public void generateOutput(); }
package com.yiibai.output.impl; import com.yiibai.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("This is Json Output Generator"); } }
package com.yiibai.output; import com.yiibai.output.IOutputGenerator; public class OutputHelper { IOutputGenerator outputGenerator; public void generateOutput() { outputGenerator.generateOutput(); } //DI via constructor public OutputHelper(IOutputGenerator outputGenerator){ this.outputGenerator = outputGenerator; } }
請參閱下面的 Spring bean 組態,Spring 將通過建構函式注入上面的 「JsonOutputGenerator」 到 「OutputHelper」 類,「public OutputHelper(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"> <constructor-arg> <ref bean="JsonOutputGenerator" /> </constructor-arg> </bean> <bean id="JsonOutputGenerator" class="com.yiibai.output.impl.JsonOutputGenerator" /> </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 Json Output Generator