Managing the Spring context
The Spring application context is where our beans are referenced to be used in our application, and managing it correctly is not a simple task. When we have dozens of beans created, where and how we access them is important, and we could end up in a situation that we refer to as an incorrect bean.
In this section, we will discuss ways to handle this complexity.
Constructor injection
In this book, we have used @Autowired
in our examples to illustrate how we ask Spring to inject a bean into our application.
Consider this example of two services and a controller that uses them:
import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.web.bind.annotation.* @Service class AccountService { fun getAccountsByCustomer(customerId: Int): List<Account> = listOf(Account(1, 125F), Account(2, 500F)) } @Service class CustomerService { @Autowired private lateinit var accountService: AccountService...