Backend Development 9 min read

Various Ways to Register Beans in the Spring IoC Container

This article explains six common techniques for adding beans to the Spring IoC container, including @Configuration with @Bean, @Component with @ComponentScan, various @Import approaches, FactoryBean, and BeanDefinitionRegistryPostProcessor, providing code examples and usage details for each method.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Various Ways to Register Beans in the Spring IoC Container

We often need to add objects to the Spring container, and this article summarizes several ways to do so.

1. @Configuration + @Bean

Declare a configuration class with @Configuration and define beans using @Bean .

@Configuration
public class MyConfiguration {
    @Bean
    public Person person() {
        Person person = new Person();
        person.setName("spring");
        return person;
    }
}

2. @Component + @ComponentScan

Mark a class with @Component and enable scanning with @ComponentScan on a configuration class.

@Component
public class Person {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    @Override
    public String toString() { return "Person{" + "name='" + name + '\'' + '}'; }
}

@ComponentScan(basePackages = "com.springboot.initbean.*")
public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

3. @Import Annotation

The @Import annotation can import configuration classes, regular components, or custom selectors.

3.1 Direct class import

public class Person { /* fields and methods */ }

@Import(Person.class)
public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = ctx.getBean(Person.class);
        System.out.println(bean);
    }
}

3.2 @Import + ImportSelector

@Import(MyImportSelector.class)
public class Demo1 { /* main method */ }

class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.springboot.pojo.Person"};
    }
}

3.3 @Import + ImportBeanDefinitionRegistrar

@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo1 { /* main method */ }

class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        registry.registerBeanDefinition("person", beanDefinition);
    }
}

3.4 @Import + DeferredImportSelector

@Import(MyDeferredImportSelector.class)
public class Demo1 { /* main method */ }

class MyDeferredImportSelector implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{Person.class.getName()};
    }
}

4. Using FactoryBean Interface

Implement FactoryBean to create beans programmatically.

@Configuration
public class Demo1 {
    @Bean
    public PersonFactoryBean personFactoryBean() {
        return new PersonFactoryBean();
    }
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = ctx.getBean(Person.class);
        System.out.println(bean);
    }
}

class PersonFactoryBean implements FactoryBean
{
    @Override
    public Person getObject() throws Exception { return new Person(); }
    @Override
    public Class
getObjectType() { return Person.class; }
}

5. Using BeanDefinitionRegistryPostProcessor

Register bean definitions during container startup.

public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        MyBeanDefinitionRegistryPostProcessor processor = new MyBeanDefinitionRegistryPostProcessor();
        ctx.addBeanFactoryPostProcessor(processor);
        ctx.refresh();
        Person bean = ctx.getBean(Person.class);
        System.out.println(bean);
    }
}

class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        registry.registerBeanDefinition("person", beanDefinition);
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}

Summary

The article outlines six methods to add beans to the Spring container: @Configuration + @Bean, @Component + @ComponentScan, various @Import strategies, FactoryBean, and BeanDefinitionRegistryPostProcessor, each accompanied by concrete code examples.

BackendJavaConfigurationSpringdependency injectionBean
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.