Close

Spring Framework - ImportBeanDefinitionRegistrar Examples

[Last Updated: Nov 9, 2025]

Spring Framework 

An implementation of ImportBeanDefinitionRegistrar can be specified with @Import so that additional objects can be registered as Spring beans during configuration time.

package com.logicbig.example;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
//there can be some conditional criteria to add the following bean
GenericBeanDefinition gbd = new GenericBeanDefinition();
gbd.setBeanClass(AppBean.class);
gbd.getPropertyValues().addPropertyValue("str", "value set from registrar");
registry.registerBeanDefinition("appBean", gbd);
}
}

package com.logicbig.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(MyBeanRegistrar.class)
public class MyConfig {

@Bean
ClientBean clientBean() {
return new ClientBean();
}
}

package com.logicbig.example;

public class AppBean {
private String str;

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

public void process() {
System.out.println(str);
}
}

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;

public class ClientBean {
@Autowired
private AppBean appBean;

public void doSomething() {
appBean.process();
}
}

package com.logicbig.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ImportBeanDefinitionRegistrarExample {

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

Output

value set from registrar
Original Post




See Also