At Component is the general one. It means, this class is a bean. At Service is a component, for business logic. At Repository is a component, for data access. And at Controller, or at Rest Controller, is a component, for the web.
Price formatter isn't a service, or a controller. It's a small helper, so we use at Component. Format turns a price into text, with a pound sign, and two decimals.
PriceFormatter.javajava
@Componentpublic class PriceFormatter { public String format(double price) { return String.format("£%.2f", price); }}
Now the service asks for the formatter, in its constructor. So Spring builds a chain. The formatter, then the service, then the controller. Run it. The prices come back formatted, with two decimals, and a pound sign.
BookService.javajava
@Servicepublic class BookService { private final PriceFormatter formatter; public BookService(PriceFormatter formatter) { this.formatter = formatter; } public List<String> priceList() { return List.of("Dune: " + formatter.format(9.99), "Circe: " + formatter.format(10.5)); }}
Output
["Dune: £9.99","Circe: £10.50"]
Also uses PriceFormatter.java
@Componentpublic class PriceFormatter { public String format(double price) { return String.format("£%.2f", price); }}
Also uses BookController.java
@RestControllerpublic class BookController { private final BookService service; public BookController(BookService service) { this.service = service; } @GetMapping("/prices") public List<String> prices() { return service.priceList(); }}
At Component, at Service, at Repository, and at Controller all make beans. Pick the one that says what the class is for. Next, at Configuration, and at Bean.