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.
Example:
Implementing ImportBeanDefinitionRegistrar
public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions (AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
GenericBeanDefinition gbd = new GenericBeanDefinition();
gbd.setBeanClass(AppBean.class);
gbd.getPropertyValues().addPropertyValue("str", "value set from registrar");
registry.registerBeanDefinition("appBean", gbd);
}
}
The configuration class and @Import
@Configuration
@Import(MyBeanRegistrar.class)
public class MyConfig {
@Bean
ClientBean clientBean () {
return new ClientBean();
}
}
The beans
public class ClientBean {
@Autowired
private AppBean appBean;
public void doSomething () {
appBean.process();
}
}
public class AppBean {
private String str;
public void setStr (String str) {
this.str = str;
}
public void process () {
System.out.println(str);
}
}
The main method
public class ImportBeanDefinitionRegistrarExample {
public static void main (String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}
} Outputvalue set from registrar
Example ProjectDependencies and Technologies Used: - Spring Context 4.3.4.RELEASE: Spring Context.
- JDK 1.8
- Maven 3.3.9
|