The repository interfaces provided by Spring Data JPA, such as CrudRepository
, are very powerful for managing data without having to write too much code. However, they are not of much use without a way for an end user of your API to interact with them.
When a user wishes to interact with your API, they do so by making REST calls to a RestController
. A RestController
is used as the layer of the application that takes requests from the user and accordingly sends commands to the repository or data access layer to accomplish what task the user requested in their REST call.
The repository must be a dependency of the controller, and you can make the repository bean available to the controller class using dependency injection.
Since the extension of the CrudRepository
will be used in the “Spring context,” it is implicitly a bean.
To make a bean available to a class that depends on it, you can simply add it as a field of the class and include it in the constructor. Spring Boot will automatically “wire” in the dependency when it discovers the dependency in the Spring context. For the PersonRepository
example, we could have a PersonController
that looks like:
import org.springframework.web.bind.annotation.RestController; import com.codecademy.people.repositories.PersonRepository; @RestController public class PersonController { private final PersonRepository personRepository; public PersonController(final PersonRepository personRepository) { this.personRepository = personRepository; } // ... all REST endpoint mappings }
To make the PersonRepository
available to the PersonController
as a dependency, all that had to be done was:
- Import the
PersonRepository
from the correct package - Add the
PersonRepository
as a field in thePersonController
class - Add the
PersonRepository
to the constructor and assign it to the field appropriately
In this exercise, you’ll do the same to enable the PlantRepository
to be used by the PlantController
class.
Instructions
Add an import
statement to PlantController.java that brings in your PlantRepository
class.
Add the PlantRepository
as a field in the PlantController
class. Ensure that this field is private
and final
, as we don’t expect other classes to access the PlantRepository
from here, and we don’t expect to change the repository class in any way; only use it.
Name the field plantRepository
to remain consistent with common conventions.
Now that the field is present in the class, all that’s left is to initialize it properly using the constructor, so that Spring Boot has a means to do the dependency injection required to make the PlantRepository
bean available to the PlantController
.
Add a constructor and use it to initialize the PlantRepository
field.