Question

Autofac is an Inversion of Control container for .net. It has this attractive (to me) feature:

When Autofac instantiates a component, it satisfies the component's dependencies by finding and instantiating other components.

Components express their dependencies to Autofac as constructor parameters:

public class TaskController : IController 
{
    public TaskController(ITaskRepository tasks) { ... }
}

In this case Autofac will look for another component that provides the ITaskRepository service and call the constructor of TaskController with that component as a parameter.

(source: http://code.google.com/p/autofac/)

For the simplest case where there's a single implementation for a given interface this works neatly - without requiring any meta-data about the dependency (attributes/XML/config class).

Does Java's "Spring DI" container support the same functionality?

Was it helpful?

Solution

I'm looking for the DI container to deduce this information from the bytecode rather than me having to supply it in XML.

I don't believe Spring has such functionality. If you could annotate your constructor like so

@Autowired
public TaskController(ITaskRepository tasks) { ... }

and there was only one bean that implements ITaskRepository in the context, then Spring could figure it out, but you'll need the annotation.


Correct me if I misunderstood your question.

If you don't have control of the class to add annotations, you can still use the <bean> <constructor-arg> element to reference and use another bean when invoking the constructor.

<bean id="taskRepository" class="com.some.TaskRepositoryImpl" />

<bean id="taskController" class="com.some.TaskController">
    <constructor-arg ref="taskRepository" />
</bean>

Alternatively, with Java configuration

@Bean
public ITaskRepository taskRepository() {
    return new TaskRepositoryImpl();
}

@Bean
public TaskController taskController() {
    return new TaskController(taskRepository());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top