Spring - Using ImportBeanDefinitionRegistrar

[Last Updated: Dec 30, 2016]

We saw in the last two tutorials that in addition to ordinary Configuration classes, @Import annotation can also process ImportSelector and DeferredImportSelector implementations. In this tutorial we are going to see one more option for @Import: ImportBeanDefinitionRegistrar.

The interface ImportBeanDefinitionRegistrar

public interface ImportBeanDefinitionRegistrar {

	public void registerBeanDefinitions(
                            AnnotationMetadata importingClassMetadata,
                            BeanDefinitionRegistry registry);


This Interface is to be implemented by types that register additional bean definitions when processing @Configuration classes.


Implementing ImportBeanDefinitionRegistrar

public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {

  public void registerBeanDefinitions (AnnotationMetadata importingClassMetadata,
                                       BeanDefinitionRegistry registry) {
      GenericBeanDefinition gbd = new GenericBeanDefinition();
      gbd.getPropertyValues().addPropertyValue("str", "value set from registrar");
      registry.registerBeanDefinition("appBean", gbd);

The configuration class and @Import

public class MyConfig {

  ClientBean clientBean () {
      return new ClientBean();

The beans

public class ClientBean {
  private AppBean appBean;

  public void doSomething () {
public class AppBean {
  private String str;

  public void setStr (String str) {
      this.str = str;

  public void process () {

The main method

public class ImportBeanDefinitionRegistrarExample {

  public static void main (String[] args) {
      ApplicationContext context =
                new AnnotationConfigApplicationContext(
      ClientBean bean = context.getBean(ClientBean.class);


value set from registrar

Example Project

Dependencies and Technologies Used:

  • Spring Context 4.3.4.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.3.9

Import Bean Def Registrar Select All Download
  • spring-import-bean-registrar
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also