AI Hints
Home›Spring Boot Tutorial›@Service, Constructor Injection and @Component and Friends
Spring Boot · Lesson 33 of 120

@Component and Friends

Four kinds of beans.

⏱ 2 min read▶ Video at 43:22🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

At Service isn't the only annotation that makes a bean. There's a small family of them, and they all do the same basic job.

  • Not just @Service
  • A small family
  • Same basic job

The stereotype annotations

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.

AnnotationUse for
@Componentany helper bean
@Servicebusiness logic
@Repositorydata access
@Controller / @RestControllerweb requests

A helper component

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
@Component
public class PriceFormatter {

    public String format(double price) {
        return String.format("£%.2f", price);
    }
}

Beans using beans

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
@Service
public 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
@Component
public class PriceFormatter {

    public String format(double price) {
        return String.format("£%.2f", price);
    }
}
Also uses BookController.java
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @GetMapping("/prices")
    public List<String> prices() {
        return service.priceList();
    }
}
Also uses _curl.sh
curl localhost:8080/prices

Summary

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.

Key takeaways
  • @Component
  • @Service, @Repository
  • @Controller
Next up: @Configuration and @Bean — beans from methods