Also known as Inversion-Of-Control (IOC), dependency injection allows the container or a framework library to inject instances of certain classes into your code directly.

This alleviates the need for factories and use of the new keyword.

There are many different options for dependency injection. Possibly the most common solution is to use the Spring Framework. As a Java developer though I’m not particularly fond of XML configuration, preferring to at least have my syntax checked by a compiler. That’s in no small part why I prefer to use Google Guice for DI, which is also much more lightweight as it’s only targeted at DI where Spring also targets MVC, AOP, etc.

Initializing Guice is relatively trivial:

    ...
    Injector injector = Guice.createInjector(getModule());
    ...

    private Module getModule() {
        return new Module() {
            public void configure(Binder binder) {
                binder.bind(UserService.class).to(UserServiceImpl.class);
            }
        };
    }

Now you can simply inject the UserService implementation into references to the interface like so:

    @Inject
    private UserService userService;

Easy isn’t it? Google Guice have great documentation with lots of examples and detail on why you should be using DI and how it can help testing.

Post a Comment

*
*