← Impulso Blog

Chain of Responsibility and multiple dependency injection with Spring Boot

In this article, we’ll demonstrate the Chain of Responsibility design pattern and show how to implement it with loose coupling in Spring Boot.

Black-and-white image of machinery for an Impulso article on Chain of Responsibility

Editorial translation by Impulso.

Introduction

Spring Boot is a framework for building stand-alone services, or serverless services, as they’re called these days. It’s part of the Spring ecosystem, which includes a wide range of libraries to help developers build their applications.

In this article, we’ll demonstrate the Chain of Responsibility design pattern and show how to implement it with loose coupling in Spring Boot.

Inversion of Control (IoC) and dependency injection

Today, IoC (Inversion of Control) is a powerful design pattern widely used, especially in Java EE applications. One way to implement this pattern is through Dependency Injection. This simply means injecting component dependencies into the classes where we declare them, using annotations specific to the framework or technology being used.

Dependency injection in Spring Boot

To annotate a class in Spring Boot, two things are required: the class must be a Component (or one of its subtypes), and the @Autowired annotation must be added.

@Component
public class AlunoService {
    // ... código omitido
}
@Component
public class MatriculaService {

// Injeção de alunoService 
    @Autowired
    private AlunoService alunoService;

In Spring Boot, we have other subtypes of @Component, such as @Repository and @Service, but they work the same way for dependency injection.

The "Chain of Responsibility" design pattern

You may have heard of this design pattern, which creates a "chain of responsibility" for your business rules. The rules are isolated in smaller classes that "pass the baton" to the next item in the list, forming a chain of responsibility.

The idea behind this design pattern is to keep these classes loosely coupled so that adding new rules doesn’t affect existing ones.

Implementation example

A more traditional way to implement this pattern is to declare all the classes that will make up these chains and then chain their calls together, as in the example below:

Example 1: Chain of Responsibility with POJOs

/// Classe model de aluno
public class Aluno {
 // dados omitidos
}

public interface IAlunoProcessor() {
 void setNext(IAlunoProcessor next);
 void chain(Aluno aluno);
}

public class FinanceiroService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public void chain(Aluno aluno) {
  // Realiza tratamentos de negócio para o financeiro
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

public class BibliotecaService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public void chain(Aluno aluno) {
  // Realiza tratamentos de negócio para a biblioteca
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

public class CantinaService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public Aluno chain(Aluno aluno) {
  // Realiza tratamentos de negócio para a cantina
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

// Classe de negócio de matrícula
public class MatriculaService {

public void matricular(Aluno aluno) {
  // Criação dos serviços
  FinanceiroService financeiroService = new FinanceiroService();
  BibliotecaService bibliotecaService = new BibliotecaService();
  CantinaService cantinaService = new CantinaService();

// Aninhamento das cadeias
  financeiroService.setNext(bibliotecaService);
  bibliotecaService.setNext(cantinaService);

You can see that there’s still some coupling, since MatriculaService needs to know about every class in the chain for the chain to run.

Multiple dependency injection in Spring Boot

A Spring Boot feature (tested here in version 2.0) lets us inject multiple components or services, filtering them by an interface or even a specific annotation.

Let’s look at the same example using Spring Boot:

// Classe model de aluno
public class Aluno {
 // dados omitidos
}

public interface IAlunoProcessor() {
 void setNext(IAlunoProcessor next);
 void chain(Aluno aluno);
}

public class FinanceiroService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public void chain(Aluno aluno) {
  // Realiza tratamentos de negócio para o financeiro
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

public class BibliotecaService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public void chain(Aluno aluno) {
  // Realiza tratamentos de negócio para a biblioteca
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

public class CantinaService implements IAlunoProcessor {
 private IAlunoProcessor next;

public void setNext(IAlunoProcessor next) {
  this.next = next;
 }

public Aluno chain(Aluno aluno) {
  // Realiza tratamentos de negócio para a cantina
  // Depois retorna o aluno para a próxima cadeia
  if (this.next != null) next.chain(aluno);
 }
}

// Classe de negócio de matrícula
public class MatriculaService {

public void matricular(Aluno aluno) {
  // Criação dos serviços
  FinanceiroService financeiroService = new FinanceiroService();
  BibliotecaService bibliotecaService = new BibliotecaService();
  CantinaService cantinaService = new CantinaService();

// Aninhamento das cadeias
  financeiroService.setNext(bibliotecaService);
  bibliotecaService.setNext(cantinaService);

// Chama o primeiro serviço, que dispara todas as cadeias.
  financeiroService.chain(aluno);
 }
} // Classe model de aluno
public class Aluno {
 // dados omitidos
}

public interface IAlunoProcessor() {
 Integer getPriority();
 void chain(Aluno aluno);
}

@Component
public class FinanceiroService implements IAlunoProcessor {

public Integer getPriority() {
  return 1;
 }

public void chain(Aluno aluno) {
  // realiza tratamentos de negócio para o financeiro...
 }
}

@Component
public class BibliotecaService implements IAlunoProcessor {
 public Integer getPriority() {
  return 2;
 }

public void chain(Aluno aluno) {
  // realiza tratamentos de negócio para a biblioteca...
 }
}

@Component
public class CantinaService implements IAlunoProcessor {
 public Integer getPriority() {
  return 3;
 }

public Aluno chain(Aluno aluno) {
  // realiza tratamentos de negócio para a cantina...
 }
}

// Classe de negócio de matrícula
@Component
public class MatriculaService {

@Autowired
 private List < IAlunoProcessor > processors;

Notice that FinanceiroService, BibliotecaService, and CantinaService are no longer tied to one another, and MatriculaService doesn’t depend on any of those three classes. That gives us loose coupling. To add a new class, simply implement IAlunoProcessor and set its priority. The enrollment service will then run it automatically.

Conclusion

Spring is a powerful framework for building Java applications, especially microservices and stand-alone applications. Using multiple dependency injection with the Chain of Responsibility pattern is one of many ways to keep business rules clear and separate from one another. This keeps the code clean and easy for all developers to understand.

So, want to learn more about frameworks? Join our Discord group!

Related articles