package com.zyiz.output; public interface IOutputGenerator { public void generateOutput(); }
package com.zyiz.output.impl; import com.zyiz.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("This is Json Output Generator"); } }
package com.zyiz.output; import com.zyiz.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.zyiz.output.OutputHelper"> <constructor-arg> <ref bean="JsonOutputGenerator" /> </constructor-arg> </bean> <bean id="JsonOutputGenerator" class="com.zyiz.output.impl.JsonOutputGenerator" /> </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 Json Output Generator