skip to content

Configuration & Component Model

The annotation model you use daily to declare beans: stereotypes, @Configuration classes with @Bean methods, component scanning and filters, and @Import with selectors and registrars. Interviewers probe here to see whether you know the difference between declaring a bean and making Spring find it.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

page 1 of 2

What does @ComponentScan do, and how do you tell it which packages to scan?

level: juniorimportance: must knowfreq 80%

answer

  1. scan packages → find @Component → register bean
  2. basePackages (String) vs basePackageClasses (type-safe)
  3. default = declaring class's package (Boot root package)
  4. recursive into subpackages
  5. @Service/@Repository meta-annotated with @Component

basics

~10 s

@ComponentScan tells Spring to search packages for classes annotated with @Component (and @Service, @Repository, @Controller) and register them as beans. You point it at packages with basePackages, e.g. @ComponentScan(basePackages = "com.app").

solid answer

~40 s

@ComponentScan is a configuration annotation that triggers classpath scanning: Spring walks the given packages, finds classes marked with stereotype annotations (@Component and its specializations @Service, @Repository, @Controller, plus anything meta-annotated with @Component), and registers each as a bean definition. You choose packages via basePackages (String names) or the type-safe basePackageClasses (marker classes; Spring scans their package). If you specify neither, it defaults to the package of the class that declares @ComponentScan — which is exactly why @SpringBootApplication (which includes @ComponentScan) is placed in a root package. Scanning is recursive into subpackages. @Configuration classes are themselves @Component-annotated, so they're picked up too. This is the mechanism behind classpath/annotation-based configuration versus explicit @Bean methods.

code

java · 8 lines
java
@Configuration
@ComponentScan(basePackages = {"com.app.web", "com.app.core"})
// type-safe alternative:
// @ComponentScan(basePackageClasses = {WebMarker.class, CoreMarker.class})
public class AppConfig { }

@Service // meta-annotated with @Component -> detected, bean name "orderService"
public class OrderService { }

go deeper

for a junior

Should know @ComponentScan finds @Component/@Service/etc. and registers them, and that basePackages selects packages.

for a middle

Should mention basePackageClasses type-safety, the default-package rule tied to @SpringBootApplication, recursion, and default bean naming.

for a senior

Should contrast scanning vs explicit @Bean, discuss meta-annotation detection, and when broad scanning is a smell.

for a principal

Should frame scanning as one strategy in the bean-definition-registration pipeline and reason about package/module boundaries and startup cost.

## What @ComponentScan is `@ComponentScan` is a Spring annotation, normally placed on a `@Configuration` class, that turns on **classpath scanning**. Instead of you declaring every bean by hand with a `@Bean` method, Spring searches ("scans") a set of packages, finds classes that carry a **stereotype annotation**, and automatically registers each one as a **bean definition** in the `ApplicationContext`. ### Stereotype annotations it detects - `@Component` — generic component. - `@Service`, `@Repository`, `@Controller`, `@RestController`, `@Configuration` — these are all **meta-annotated** with `@Component`, so scanning finds them too. Spring detects any class whose annotations transitively include `@Component`. ### Choosing packages - `basePackages` — one or more package names as Strings: `@ComponentScan(basePackages = {"com.app.web", "com.app.core"})`. `value` is an alias, so `@ComponentScan("com.app")` works. - `basePackageClasses` — type-safe alternative: you pass classes (often empty marker interfaces) and Spring scans the package **each class lives in**. Refactoring/renaming a package won't silently break this, unlike a hardcoded String. - **Default when nothing is given:** the package of the class that declares the annotation. That's the crucial default behind Spring Boot — `@SpringBootApplication` is a composed annotation that includes `@ComponentScan`, so putting your main class in a top-level package (e.g. `com.app`) makes Spring scan `com.app` and everything beneath it. ### Recursion Scanning is **recursive**: naming `com.app` also scans `com.app.web`, `com.app.core.impl`, etc. A common bug is placing a bean **outside** the scanned root (e.g. `com.other`) — it silently won't be registered. ### How it relates to bean definitions Each detected class becomes a `BeanDefinition`. By default the **bean name** is the simple class name with the first letter lowercased (`OrderService` → `orderService`), produced by `AnnotationBeanNameGenerator`. You can override the name via the stereotype's `value`, e.g. `@Service("orders")`. ### XML equivalent In XML config the same thing is `<context:component-scan base-package="com.app"/>`. ### When to use - Use component scanning for **your own application classes** you control and annotate. - Use explicit `@Bean` methods for **third-party classes** you can't annotate, or when you need constructor arguments/conditional wiring. ### Gotchas - Scanning too broad a package (e.g. an empty String or a very high package) is slow and may pick up unintended beans; scan only what you own. - A class must be **concrete and instantiable** and have a usable constructor to become a bean; abstract classes/interfaces are skipped (unless matched by custom filters as candidates). - Only annotated classes are found by default — a plain POJO with no stereotype is invisible to scanning.

  • Why does the location of the @SpringBootApplication class matter?
    @SpringBootApplication bundles @ComponentScan with no basePackages, so it defaults to the main class's own package and scans it recursively. Put the class in a root package or beans in sibling packages won't be found.
  • What's the default bean name for a scanned class?
    The uncapitalized simple class name (OrderService -> orderService), generated by AnnotationBeanNameGenerator. Override it via the stereotype value, e.g. @Service("orders").

saying these in an interview costs you the question

  • Thinking @ComponentScan registers every class on the classpath rather than only annotated stereotypes
  • Believing scanning is not recursive into subpackages
  • Claiming a plain POJO without any annotation gets picked up by default scanning
  • Not knowing the default is the declaring class's package

context

open as a page

What is @Conditional and the Condition interface in Spring, and how do you use them to register a bean only under certain circumstances?

level: juniorimportance: must knowfreq 62%

basics

~10 s

@Conditional is an annotation you put on a @Bean or @Configuration. It points to a class implementing the Condition interface, whose matches() method returns true/false. Spring registers the bean only when matches() returns true.

open as a page

What are @Configuration and @Bean, and how do you use them to define a Spring bean?

level: juniorimportance: must knowfreq 82%

basics

~10 s

@Configuration marks a class as a source of bean definitions. Inside it, a method annotated with @Bean returns an object that Spring registers as a bean in the application context, managing its lifecycle.

open as a page

What is functional (programmatic) bean registration in Spring, and how does it differ from declaring beans with @Bean or @Component?

level: juniorimportance: must knowfreq 55%

basics

~10 s

It registers beans by calling code — e.g. context.registerBean(MyService.class, MyService::new) — instead of using @Component scanning or @Bean methods. You give Spring a name, a type, and a lambda that creates the instance.

open as a page

What is Spring's @Import annotation and what kinds of classes can you import with it?

level: juniorimportance: must knowfreq 55%

basics

~10 s

@Import lets one Java @Configuration class pull in beans defined in another. You can import other @Configuration classes, ImportSelector or ImportBeanDefinitionRegistrar implementations, and (since Spring 4.2) plain component classes.

open as a page

What are Spring stereotype annotations, and what is the relationship between @Component and @Service / @Repository / @Controller?

level: juniorimportance: must knowfreq 80%

basics

~10 s

Stereotype annotations mark a class as a Spring-managed bean so component scanning picks it up. @Component is the base; @Service, @Repository, and @Controller are specializations of @Component for the service, persistence, and web layers.

open as a page

How do includeFilters and excludeFilters work, and what are the FilterType options?

level: middleimportance: must knowfreq 60%

basics

~10 s

@ComponentScan can narrow what it registers using includeFilters (register extra matching classes) and excludeFilters (skip matching classes). Each filter has a FilterType: ANNOTATION, ASSIGNABLE_TYPE, ASPECTJ, REGEX, or CUSTOM.

open as a page

Explain full mode vs lite mode for @Bean methods. What does CGLIB enhancement of @Configuration classes actually do?

level: middleimportance: must knowfreq 74%

basics

~20 s

In a @Configuration class (full mode), Spring CGLIB-subclasses it so calling one @Bean method from another returns the cached singleton, not a new object. @Bean methods in a plain class (lite mode) aren't intercepted, so each direct call runs the method again.

open as a page

Walk through the registerBean overload that takes a Supplier and BeanDefinitionCustomizer varargs. What does each argument do and what can you customize?

level: middleimportance: must knowfreq 45%

basics

~20 s

registerBean(Class, Supplier, BeanDefinitionCustomizer...): the Class is the bean type, the Supplier is a lambda that creates the instance, and each BeanDefinitionCustomizer is a lambda that tweaks the BeanDefinition — e.g. set scope, primary, or lazy.

open as a page

What is an ImportSelector, and how does selectImports work?

level: middleimportance: must knowfreq 45%

basics

~20 s

ImportSelector is a Spring interface with one method, selectImports(AnnotationMetadata), that returns an array of fully-qualified class names. Spring imports each returned class as if you had listed it in @Import, letting you choose configs dynamically.

open as a page

What extra behavior does @Repository provide beyond making a class a bean, and how does persistence exception translation actually work?

level: middleimportance: must knowfreq 65%

basics

~10 s

@Repository marks persistence classes and enables automatic translation of native, technology-specific exceptions (like JDBC SQLException or JPA PersistenceException) into Spring's consistent DataAccessException hierarchy, so callers don't depend on the underlying data-access API.

open as a page

What is ConfigurationCondition and ConfigurationPhase, and why is the phase important for conditions like @ConditionalOnMissingBean?

level: seniorimportance: must knowfreq 45%

basics

~10 s

ConfigurationCondition extends Condition and adds getConfigurationPhase(), returning PARSE_CONFIGURATION or REGISTER_BEAN. It tells Spring when to evaluate the condition. 'Missing bean' checks use REGISTER_BEAN so they run after all bean definitions are known.

open as a page

What is @Indexed and the compile-time candidate component index in Spring, and why does it exist?

level: juniorimportance: should knowfreq 15%

basics

~10 s

@Indexed marks a class or stereotype so a build-time tool records it in a file, META-INF/spring.components. At startup Spring reads that file instead of scanning the whole classpath, which makes startup faster.

open as a page

How do you enable the candidate index in a build, and what exactly does the generated META-INF/spring.components file contain?

level: middleimportance: should knowfreq 18%

basics

~20 s

Add the spring-context-indexer as an annotation processor (Maven optional dependency or Gradle annotationProcessor). It runs at compile time and writes META-INF/spring.components, where each line maps a class name to the comma-separated stereotype annotations it has.

open as a page

When should you prefer component scanning over explicit @Bean methods, and what are the tradeoffs?

level: middleimportance: should knowfreq 35%

basics

~10 s

Use component scanning (@Component/@ComponentScan) for your own annotated classes — it's concise and auto-wires by constructor. Use explicit @Bean methods for third-party classes you can't annotate or when you need custom construction/conditional logic.

open as a page

What does ConditionContext give a Condition access to, and what can you realistically inspect from it?

level: middleimportance: should knowfreq 40%

basics

~10 s

ConditionContext is the first argument to matches(). It exposes the BeanDefinitionRegistry, the (possibly null) ConfigurableListableBeanFactory, the Environment, the ResourceLoader, and the ClassLoader — enough to check properties, classpath, and already-registered bean definitions.

open as a page

How do initMethod and destroyMethod on @Bean work, and how do they compare to other lifecycle callbacks?

level: middleimportance: should knowfreq 45%

basics

~10 s

@Bean(initMethod="...") names a method Spring calls after the bean is created and dependencies are set; @Bean(destroyMethod="...") names one called on shutdown. They let you run setup/cleanup on third-party classes without annotations.

open as a page

What is BeanDefinitionBuilder and how do you use it to register a bean programmatically with a BeanDefinitionRegistry?

level: middleimportance: should knowfreq 30%

basics

~10 s

BeanDefinitionBuilder is a fluent helper to build a BeanDefinition. You call BeanDefinitionBuilder.genericBeanDefinition(MyBean.class), chain addPropertyValue/addConstructorArgValue/setScope, call getBeanDefinition(), then register it via registry.registerBeanDefinition(name, definition).

open as a page

What does @ImportResource do and when would you use it?

level: middleimportance: should knowfreq 30%

basics

~10 s

@ImportResource loads bean definitions from external resource files — typically XML — into a Java @Configuration class. You point it at locations like "classpath:legacy-beans.xml", and those beans join the same context.

open as a page

How do @Controller and @RestController relate to stereotype annotations, and what does @RestController add?

level: middleimportance: should knowfreq 55%

basics

~20 s

@Controller is a @Component specialization Spring MVC detects to route web requests to handler methods. @RestController is a composed annotation = @Controller + @ResponseBody, so every handler's return value is serialized directly to the response body (typically JSON) instead of resolving a view.

open as a page

When does ClassPathScanningCandidateComponentProvider actually USE the index versus fall back to full classpath scanning?

level: seniorimportance: should knowfreq 12%

basics

~20 s

Spring uses the index only if a spring.components file exists AND every include filter is one the index can answer — annotation filters on @Indexed-marked annotations, or assignable-type filters. If any filter isn't index-supported (e.g. a regex or custom filter), it silently falls back to normal scanning.

open as a page

How are bean names assigned during component scanning, and how do you customize them with BeanNameGenerator?

level: seniorimportance: should knowfreq 30%

basics

~20 s

By default a scanned bean's name is the class's simple name with a lowercased first letter (OrderService → orderService), or the value you pass to the stereotype (@Service("x")). You override the strategy with a BeanNameGenerator via @ComponentScan(nameGenerator = ...).

open as a page

What is ClassPathScanningCandidateComponentProvider and when would you use it directly?

level: seniorimportance: should knowfreq 30%

basics

~20 s

It's the low-level engine behind @ComponentScan: given base packages and filters, it scans the classpath and returns candidate BeanDefinitions. You use it directly to find annotated/typed classes yourself — outside the normal bean registration flow.

open as a page

What does @Configuration(proxyBeanMethods = false) do, and when would you set it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

It keeps @Configuration semantics but skips CGLIB enhancement, so the class isn't proxied. @Bean methods then behave like lite mode: direct inter-bean calls create new objects. Use it when methods don't call each other, to speed startup and help native images.

open as a page

Explain Spring's Kotlin bean-definition DSL (the beans { } block). How is it structured, how does it wire dependencies, and how do you plug it into an application?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The beans { } DSL builds bean definitions in Kotlin without annotations. Inside it you write bean<Foo>() to register a type, or bean { Bar(ref()) } to construct one and pull dependencies with ref(). It returns a BeanDefinitionDsl you initialize against a GenericApplicationContext.

open as a page

How does DeferredImportSelector differ from a plain ImportSelector, and why does auto-configuration use it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A plain ImportSelector runs inline while its config class is parsed. A DeferredImportSelector runs after all @Configuration classes have been processed. That late timing lets Spring Boot auto-configuration apply last, so user-defined beans and @Conditional checks take precedence.

open as a page

What is an ImportBeanDefinitionRegistrar and when do you choose it over an ImportSelector?

level: seniorimportance: should knowfreq 35%

basics

~20 s

ImportBeanDefinitionRegistrar is a Spring hook referenced from @Import. Its registerBeanDefinitions method gives you the BeanDefinitionRegistry so you can build and register BeanDefinitions programmatically — ideal when the number or shape of beans is dynamic, like scanning for interfaces.

open as a page

How would you create a custom stereotype annotation via meta-annotation composition, and why?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Define your own annotation and meta-annotate it with @Component (and any others you want to bundle, like @Scope or @Transactional). Component scanning treats classes with your annotation as beans because @Component is present transitively.

open as a page

How does Spring Boot build @ConditionalOnClass and @ConditionalOnMissingBean on top of the @Conditional mechanism, and what ordering rules make auto-configuration back-off deterministic?

level: principalimportance: should knowfreq 33%

basics

~20 s

Boot's conditions are meta-annotations: each is annotated with @Conditional pointing to a Spring Condition implementation (e.g. OnClassCondition, OnBeanCondition). They read attributes via AnnotatedTypeMetadata. OnBeanCondition runs in the REGISTER_BEAN phase, and Boot parses user config before auto-config so user beans win.

open as a page

When would you choose functional bean registration (registerBean / Kotlin DSL) over annotations, and what are the performance, AOT/native-image, and design trade-offs?

level: principalimportance: should knowfreq 22%

basics

~20 s

Choose functional registration for library code that shouldn't force scanning, dynamic sets of beans (one per config entry), and reflection-free startup for GraalVM native / Spring AOT. Trade-off: you lose annotation discoverability and must wire dependencies explicitly.

open as a page

showing 1–30 of 36