Skip to main content
IoC and dependency injection · Topic 7 of 7

Component scanning and stereotypes

Definition​

Component scanning makes Spring search a package for classes marked @Component and register them as beans. @Service, @Repository and @Controller are the same thing with a clearer meaning, and @Repository also translates database exceptions.

Example code​

Finding beans by scanning

import java.util.Arrays;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Component class Clock2 { }
@Service class BillingService { }
@Repository class CustomerRepository { }
class NotABean { } // no stereotype: Spring ignores it

@ComponentScan // scans this class's package
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
String[] names = context.getBeanDefinitionNames();
Arrays.stream(names).filter(n -> !n.contains(".") && !n.equals("demo")).sorted().forEach(System.out::println);
}
}
}

// Output:
// billingService
// clock2
// customerRepository

Finished this page? Track your progress (saved only in your browser).