Java vs. Ruby: Dependency Injection

Java using the Spring framework:

<!-- beans.xml -->
<?xml version="1.0" encoding="UTF-8"?>
  <bean id="warmer" class="examples.Warmer">
    <property name="heater"><ref bean="heater"/></property>
    <property name="potSensor"><ref bean="potSensor"/></property>
  <bean id="heater" class="examples.Heater"/>
  <bean id="potSensor" class="examples.PotSensor"/>
  <bean id="boiler" class="examples.Boiler"/>
  <bean id="coffeeMaker" class="examples.CoffeeMaker">
    <property name="warmer"><ref bean="warmer"/></property>
    <property name="boiler"><ref bean="boiler"/></property>
// java
InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
CoffeeMaker coffeeMaker = (CoffeeMaker)factory.getBean("coffeeMaker");

Ruby equivalent using the DIM framework:

container =
container.register(:warmer) { |c|, c.pot_sensor) }
container.register(:heater) { }
container.register(:pot_sensor) { }
container.register(:boiler) {  }
container.register(:coffee_maker) { |c|, c.boiler) }
coffee_maker = container.coffee_maker

Jim Weirich’s DIM framework is less than 30 lines of code. I don’t know how many lines of code for Spring.

Reference: DIM

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply