12
Jun

Dependency injection with Guice

Step 1:
=======

public interface Discountable {
double getDiscount();
}

Step 2: Implement above interface
===================================

public class EarlyBirdDiscount implements Discountable {

@Override
public double getDiscount() {
return .25;
}
}

and

public class NightOwlDiscount implements Discountable {

@Override
public double getDiscount() {
return 0.35;
}
}

Step 3:
=======

import com.google.inject.Inject;

public class CheckoutService {

private final Discountable discountable;

@Inject
public CheckoutService(Discountable obj) {
this.discountable = obj;
}

public double checkout(double shoppingCartVal) {
double totoal = shoppingCartVal – (shoppingCartVal * discountable.getDiscount());
return totoal;
}
}

Step 4:
=======

import com.google.inject.AbstractModule;

public class DiscountGuiceModule extends AbstractModule {

@Override
protected void configure() {
bind(Discountable.class).to(NightOwlDiscount.class);
}

}

Step 5:
=======

import com.google.inject.Guice;
import com.google.inject.Injector;

public class Main {

public static void main(String[] args) {
Injector guice = Guice.createInjector(new DiscountGuiceModule());

CheckoutService service = guice.getInstance(CheckoutService.class);
System.out.println(service.checkout(199.99D));
}
}

Output:
=======

129.9935

Example from web:

Google Guice Dependency Injection Example Tutorial

Sample projects for Guice DI / IOC:
===================================
SampleProject4GuiceDependencyInjectionzip