Spring Dependency Injection

  • @Service is telling spring to have it as a spring bean component in the spring context
  • @Autowire is telling Spring to inject those classes form the spring context

Note: Avoid using concrete classes where possbile, in our example of TodoService:

  • We are injecting a MessageService instead of the concrete implementation (Eg: EmailService or SMSService)
  • Spring will inject the concrete class by default if there is only 1 concrete class (See section Qualifiers to see how to manage multiple concrete classes)

@Autowire on constructor (Preferred approach)

@Service
public class TodoService {

    private final TodoRepository todoRepository;

    private final MessageService messageService;

    @Autowired
    public TodoService(TodoRepository todoRepository,
                       MessageService messageService) {
        this.todoRepository = todoRepository;
        this.messageService = messageService;
    }

    public TodoJava saveTodo(TodoJava todo) {
        messageService.sendMessage("0441111111", todo.getName());
        return todoRepository.save(todo);
    }

    public Optional<TodoJava> findTodo(Long id) {
        return todoRepository.findTodoJavaById(id);
    }

}

@Autowire on fields

@Service
public class TodoService {

    @Autowired
    private final TodoRepository todoRepository;

    @Autowired
    private final MessageService messageService;

    public Todo saveTodo(TodoJava todo) {
        messageService.sendMessage("0441111111", todo.getName());
        return todoRepository.save(todo);
    }

    public Optional<Todo> findTodo(Long id) {
        return todoRepository.findTodoById(id);
    }

}

@Autowire on setters

@Service
public class TodoService {

    private TodoRepository todoRepository;

    private MessageService messageService;

    public Todo saveTodo(TodoJava todo) {
        messageService.sendMessage("0441111111", todo.getName());
        return todoRepository.save(todo);
    }

    public Optional<Todo> findTodo(Long id) {
        return todoRepository.findTodoById(id);
    }

    @Autowire
    public setTodoRepository(TodoRepository todoRepository){
        this.todoRepository = todoRepository; 
    }
}

results matching ""

    No results matching ""