programming

Overuse of Dependency Injection Framework

If it can be wired with a dependency injection framework, it does not mean, that it should be.

Example: everything is wired with dependency injection framework

Let’s have an entity Foo, a service FooService and a repository FooRepository.

We will be using Spring framework as dependency injection framework. We define the bean fooRepository.

<bean id="fooRepository" class="FooRepositoryImpl"></bean>

The bean is managed by the Spring framework. The class FooRepositoryImpl implements the interface FooRepository.

We create the class FooService, which uses fooRepository.

public class FooServiceImpl implements FooService {

    FooRepository fooRepository;

    public FooService(FooRepository fooRepository) {
        this.fooRepository = fooRepository;
    }
}

We have to wire them together. We use the dependency injection framework. The configuration in the Spring framework:

<bean id="fooService" class="FooServiceImpl">
    <constructor-arg ref="fooRepository"/>
</bean>

The main method will look like:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml"); //get Spring context

    FooService fooService = (FooService) context.getBean("fooService");

    fooService.doStuff();
}

Do we really need to make a managed bean FooService?

Example: FooService is not wired with dependency injection framework

We will create FooService as new object. Let’s look new main method:

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml"); //get Spring context

    FooRepository fooRepository = (FooRepository) context.getBean("fooRepository");
    FooService fooService = new FooService(fooRepository);

    fooService.doStuff();
}

Conclusion

It maybe seems, that there is no difference in examples. When I was creating a domain model, I did not want to have a dependency framework in the domain model, but I wanted to wire some objects together. I wanted something like Onion Architecture. On top level I define dependencies with the dependency framework, e.g., dependencies to database, external services. Those dependencies were used in lower levels through interfaces. The need to wire everything with dependency framework has to go away.

Leave a Reply