When to use the constructor injector in Spring?

When to use the constructor injector in Spring?

I've heard that constructor injection is especially useful when you absolutely need an instance of a dependency class before your component is used. But what does this mean?

Can anyone explain to me the following points with simple examples:

  • What benefits will I get using the constructor injector?
  • What is dynamic constructor injection?
+5


source to share


1 answer


The correct approach is to use the constructor injector whenever possible. This makes it clear what the dependencies of the object are, and you cannot create it unless you provide everything you need.

Use the constructor as shown below.

public class ProjectService {
    private final ProjectRepository projectRepository;
    private final TaskRepository taskRepository;

    public ProjectService(TaskRepository taskService, ProjectRepository projectService) {
        Assert.notNull(taskService);
        Assert.notNull(projectService);

        this.taskRepository = taskService;
        this.projectRepository = projectService;
    }

    public Project load(Long projectId) {
        return projectRepository.findById(projectId);
    }
}

      

  • final

    fields ensure dependencies are not changed after object initialization
  • Assert.notNull

    makes sure you don't put null values ​​in place of real objects.

When you use setter injection or field injection, your API allows you to create an object in the wrong state. Let's consider an example:



public class ProjectService {
    private ProjectRepository projectRepository;
    private TaskRepository taskRepository;

    public Project load(Long projectId) {
        return projectRepository.findById(projectId);
    }

    @Autowired
    public void setProjectRepository(ProjectRepository projectRepository) {
        this.projectRepository = projectRepository;
    }

    @Autowired
    public void setTaskRepository(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }
}

      

ProjectService projectService = new ProjectService();
projectService.load(1L); // NullPointerException is thrown

      

For all optional dependencies, you can use the install method. Find out more on Oliver Gierke's blog (leading data source): http://olivergierke.de/2013/11/why-field-injection-is-evil/

Update 15.01.2019

Since Spring 4.3, there is no need to put an annotation @Autowired

in a constructor if only one constructor is present.

+10


source







All Articles