skip to content

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

level: juniorimportance: must knowfreq 55%

answer

  1. Java equivalent of XML <import/>
  2. 4 targets: @Configuration, plain class, ImportSelector, Registrar
  3. engine behind @EnableXxx
  4. imports are de-duplicated
  5. must be on a processed config class

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.

solid answer

~30 s

@Import is a class-level annotation used on a @Configuration class to combine configuration from other sources into one context, replacing XML's <import/>. Its value is an array of classes and it accepts four kinds: (1) other @Configuration classes, whose @Bean methods are added; (2) plain component classes (since 4.2), registered as beans; (3) ImportSelector implementations, whose selectImports() returns class names to import programmatically based on conditions/metadata; (4) ImportBeanDefinitionRegistrar implementations, which register BeanDefinitions directly against the registry. It's the mechanism behind @EnableXxx annotations, which are usually just meta-annotated with @Import. Imports are de-duplicated, so importing the same class twice is harmless.

code

java · 12 lines
java
@Configuration
@Import({ DataConfig.class, SecurityConfig.class, MetricsRegistrar.class })
public class AppConfig {
    // beans from DataConfig and SecurityConfig are now part of this context;
    // MetricsRegistrar registers extra beans programmatically
}

// A custom @Enable annotation is just a meta-annotated @Import:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(SchedulingConfiguration.class)
public @interface EnableMyScheduling { }

go deeper

for a junior

Know it merges another config's beans into your context and is the Java version of XML <import/>.

for a middle

List all four import targets and connect @Import to how @EnableXxx annotations are built.

for a senior

Discuss de-duplication, placement requirements, and choosing @Import vs @ComponentScan vs @ImportResource.

for a principal

Frame @Import as the extensibility seam libraries expose via @EnableXxx, and reason about parse-time ordering of selectors/registrars.

**@Import** (`org.springframework.context.annotation.Import`) is a type-level annotation placed on a class that Spring processes as a *configuration class* (typically annotated with `@Configuration`). It is the Java-config equivalent of the XML `<import resource="..."/>` element: it lets you assemble one application context out of several smaller configuration sources instead of one giant config. **Definition of terms:** A *bean* is an object the Spring container creates and manages. A *@Configuration class* is a Java class whose `@Bean`-annotated methods define beans. A *BeanDefinition* is the container's internal metadata description of a bean (its class, scope, dependencies) before the object is instantiated. The *BeanDefinitionRegistry* is the container-side registry those definitions live in. **The four things @Import can accept** (`value` is a `Class<?>[]`): 1. **Other @Configuration classes** — all of their `@Bean` methods and nested config are merged in. This is the everyday use: `@Import({DataConfig.class, WebConfig.class})`. 2. **Regular component classes (since Spring 4.2)** — any plain class (even without `@Component`) named in `@Import` is registered as a single bean of that type. Handy to register a bean without component-scanning its package. 3. **`ImportSelector` implementations** — a hook whose `selectImports(AnnotationMetadata)` method returns an array of fully-qualified class names to import *as if* they had been listed in `@Import`. This enables conditional/dynamic imports. 4. **`ImportBeanDefinitionRegistrar` implementations** — a lower-level hook that receives the `BeanDefinitionRegistry` and registers `BeanDefinition`s programmatically. Used when you need to register a *variable number* of beans or beans built at parse time (e.g. `@MapperScan`, `@EnableFeignClients`). **How @Enable annotations use it:** Annotations like `@EnableScheduling`, `@EnableAsync`, `@EnableWebMvc`, `@EnableTransactionManagement` are almost always just custom annotations meta-annotated with `@Import(SomeConfiguration.class)` or `@Import(SomeSelector.class)`. So learning `@Import` explains the whole `@EnableXxx` family. **Edge cases & gotchas:** - **De-duplication:** importing the same configuration class from multiple places registers its beans only once — Spring tracks imported classes. - **Placement:** `@Import` must sit on a class that actually gets processed as a configuration class (a `@Configuration` class, an `@Enable*`-annotated app class, or a component-scanned `@Component`). Putting it on a random unscanned class does nothing. - **Ordering:** regular imports are processed while the importing config class is parsed; `ImportSelector`/`ImportBeanDefinitionRegistrar` run at specific points in that parse (see `DeferredImportSelector` for the deferred variant). - **Not a replacement for component scanning:** `@Import` is explicit and targeted; `@ComponentScan` is broad discovery. They compose. - **XML:** to import *XML*-defined beans into Java config you use the separate `@ImportResource`, not `@Import`. **When to use:** to modularize configuration, to build reusable library `@EnableXxx` annotations, and to register beans conditionally or programmatically without XML.

  • What's the difference between @Import and @ComponentScan?
    @Import explicitly names specific classes/selectors/registrars to add; @ComponentScan broadly discovers @Component-stereotyped classes under given packages. @Import is targeted and works well for library-provided config; scanning is for your own application beans.
  • How would you import beans that are defined in an XML file?
    Use @ImportResource("classpath:beans.xml") on a @Configuration class. @Import only takes classes; @ImportResource takes resource locations and delegates to an XML (or Groovy) bean-definition reader.

saying these in an interview costs you the question

  • Saying @Import can import XML files (that's @ImportResource)
  • Claiming @Import only works with @Configuration classes (plain components and selectors/registrars also work)
  • Thinking importing the same config twice duplicates its beans

context