Dependency Injection

With dependency injection we give our class the attributes it needs through the constructor or the setter. If an attribute is required hand it through the constructor is the preferred way (in frameworks like Spring it’s advised by the framework).

A dependency injection example for bread looks like this.
water

public class Water {
    private String name;
    private double price;

    public Water(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return name;
    }
}

flour

public class Flour {
    private String name;
    private double price;

    public Flour(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return name + " flour";
    }
}

bread

public class Bread {
    private Flour flour;
    private Water water;

    public Bread(Flour flour, Water water) {
        this.flour = flour;
        this.water = water;
    }

    @Override
    public String toString() {
        return flour + " with " + water + " is bread.";
    }
}

Main

public static void main(String[] args) {
    Water water = new Water("normal water", 0.01);
    Flour flour = new Flour("grain", 0.88);
    Bread bread = new Bread(flour, water);
    System.out.println(bread);
}

With the following output.

grain flour with normal water is bread.

As you can see we hand in all the classes needed for bread through it’s constructor. If we want to make one part different we hand it a different class of water. This enables us to change the outcome of the class. while having to change only one part of the class (the class used during instantiation).

If we use an interface in the constructor we can combine the interface segregation principle with the liskov substitution principle and dependency injection. This helps us decouple our code immensely.

This is the concept that is used in the Spring framework but they hide it away with a inversion of control container (IoC). @Component makes the container aware of the class. @Autowired injects the dependency in the constructor or setter. This way we don’t have to use the new keyword our self.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s