Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 66 ยท Inversion of Control and Beans

Component Scanning and Stereotypes

How Spring Boot finds beans: @Component, @Service, @Repository, @Controller, scan packages, bean names and the meta-annotations behind @SpringBootApplication.

In the previous lesson the container built objects from constructor parameters, but we still told it which classes exist. In a real application you do not list your beans one by one. You put an annotation on each class, and at startup Spring scans the classpath for annotated classes and registers them as beans. This is component scanning, and the annotations it looks for are called stereotypes.

This lesson explains the four main stereotypes and what each one means, where scanning looks, how beans are named, how @SpringBootApplication fits in, and how to write your own stereotype by combining annotations. Real Spring code is read-only; a runnable stand-in implements a small scanner with custom annotations, including the meta-annotation trick that makes stereotypes work.

The stereotypes

Spring's base annotation is @Component: "this class is a bean, please manage it". Three more annotations are specializations of it:

Java
@Component          // generic bean
public class SlugGenerator { ... }

@Service            // business logic
public class OrderService { ... }

@Repository         // data access
public class JdbcOrderRepository implements OrderRepository { ... }

@Controller         // web layer (returns view names)
public class PageController { ... }

@RestController     // @Controller + @ResponseBody (returns data)
public class OrderApi { ... }

One base, several flavors

@Component The generic bean. Everything else builds on it.
@Service Business rules. Marks intent only.
@Repository Data access. Adds exception translation.
@Controller Web layer. Handles requests.

Each of the last three is itself annotated with @Component.

1 / 2

How different are they really?

  • @Service has no extra behavior. It tells readers (and tools) that the class holds business logic. You could use @Component, but the name documents the layer.
  • @Repository adds one real feature: persistence exceptions thrown by JDBC, JPA or Hibernate are translated into Spring's DataAccessException hierarchy, so service code is not tied to one technology's exceptions.
  • @Controller and @RestController are recognized by Spring MVC, which looks for request-mapping methods on these beans. @RestController additionally writes return values directly to the response body, as you will see in REST Controllers.
  • @Configuration is also a @Component; it marks a class whose @Bean methods declare beans (@Configuration and @Bean).

Choose the most specific stereotype that is true. A class is a service if it holds business rules; do not call everything @Component.

How scanning decides

The scanner takes a base package and examines every class in it and in all sub-packages. A class becomes a bean when it carries a stereotype annotation, directly or indirectly. "Indirectly" matters: @Service is not special-cased by the scanner. @Service is itself annotated with @Component, and Spring's scanner follows such meta-annotations:

Java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface Service {
    @AliasFor(annotation = Component.class)
    String value() default "";
}

That is why you can define your own stereotypes by stacking annotations, and why @SpringBootApplication can switch on three features at once. The first TryIt is a mini scanner built on exactly this mechanism: our own @MiniComponent, a @MiniService that carries it as a meta-annotation, and a scanner that checks annotations recursively.

Java Meta-annotations make stereotypes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

CancelOrder is annotated only with @UseCase, a custom annotation that stacks on @MiniService, which stacks on @MiniComponent. The scanner finds it, and its default bean name is cancelOrder.

In real Spring you can do the same: define @UseCase as an annotation that is itself annotated with @Service (and perhaps @Transactional), and every class carrying it is a transactional service bean.

Bean names

Every bean has a name. For a scanned class the default is the simple class name with a lowercase first letter: OrderService becomes orderService. Override it in the annotation:

Java
@Service("billing")
public class BillingService { ... }

Names matter when two beans share a type and you must pick one (Qualifiers, @Primary and Collections), and when you debug with the Actuator beans endpoint. If two scanned classes in different packages have the same simple name, they collide on the default name and startup fails with a conflict; give one an explicit name.

Where scanning looks

@SpringBootApplication includes @ComponentScan with no arguments, which means: scan the package of the annotated class and everything below it. This is why the main class belongs in the root package of your project, as the project layout lesson said.

If you must scan elsewhere, say so explicitly (read-only):

Java
@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.shared"})
public class DemoApplication { ... }

Do not scan the whole com package: it slows start-up and can register beans from libraries you did not intend. And do not move the main class into a sub-package "to tidy up", or siblings of that package vanish from the scan.

Remember the limits of scanning: it registers classes annotated with a stereotype. An annotated interface is not instantiated, an abstract class cannot be a bean, and a class without annotation is invisible (declare it with an @Bean method instead, which is also how you add classes from libraries you cannot annotate).

The second TryIt models the base-package rule: the same "classpath" scanned from two different roots.

Java Scan from a root package

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

PriceFormatter has no annotation, so no root finds it. AuditService has an annotation but sits outside the root, so scanning from com.example.demo never reaches it. These two situations cause most "why is my bean missing" questions.

What @SpringBootApplication really is

Putting it together, this annotation is a meta-annotation:

Java
@SpringBootConfiguration      // a @Configuration: this class may declare @Bean methods
@EnableAutoConfiguration      // add infrastructure beans from the classpath
@ComponentScan                // scan this package and below
public @interface SpringBootApplication { ... }

@SpringBootConfiguration is itself a @Configuration, which is a @Component. So your main class is a bean too, and you can add @Bean methods directly to it, though larger apps keep configuration in separate classes. Scanning excludes auto-configuration classes, because those are loaded by a different mechanism you will study in How Auto-Configuration Works.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about @Service is correct?

    @Service is meta-annotated with @Component, so it registers a bean; it adds no extra behavior but communicates intent.
  2. 2. What extra behavior does @Repository provide?

    Spring wraps repository beans so technology-specific exceptions become DataAccessException subclasses.
  3. 3. The main class is in com.example.demo; AuditService (annotated with @Service) is in com.example.other. What happens?

    Scanning covers the main class's package and sub-packages only.
  4. 4. What is the default bean name of class OrderService annotated with @Service?

    The default name is the simple class name with a lowercase first letter. You can override it with the annotation's value.

Summary

  • Component scanning finds classes annotated with a stereotype in the base package and its sub-packages and registers them as beans.
  • @Component is the base; @Service (intent), @Repository (exception translation), @Controller/@RestController (web) specialize it.
  • Scanning follows meta-annotations, so you can create your own stereotype by stacking annotations.
  • The default bean name is the lowercase-first class name; override it with the annotation value.
  • @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan; keep the main class in the root package or use scanBasePackages.
  • Unannotated classes and classes outside the scanned packages are invisible; declare them with @Bean or widen the scan.

Next: @Configuration and @Bean.