Spring Bean Alias in JavaConfig

前端 未结 3 1941
一整个雨季
一整个雨季 2021-01-11 18:50

I have a @Service annotated class which provides core functionality which I can use in all my projects:

@Service
public class MyService {}
         


        
3条回答
  •  旧时难觅i
    2021-01-11 19:44

    With small amount of configuration and one ImportBeanDefinitionRegistrar you can configure bean aliases via Java configuration. You can check bean-alias library project for reference - developed for the needs of my projects. Feel free to modify and/or copy the source into your own project in case the spring version used in it does not work with your setup.

    Once you have the library on your path, you declare an alias through the annotation:

    @Configuration
    @BeanAlias(name = "fromName", alias = "toName")
    public class ExampleConfiguration {
    }
    

    That's it.

    How it works is that with the annotation we import a ImportBeanDefinitionRegistrar implementation

    @Import(BeanAliasBeanRegistrar.class)
    public @interface BeanAlias {
    }
    

    which registers the alias in the BeanDefinitionRegistry

    class BeanAliasBeanRegistrar implements ImportBeanDefinitionRegistrar, PriorityOrdered {
    
        @Override
        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
          ...
          registerAlias(registry, metadata.getAnnotationAttributes(BeanAlias.class.getName()));
        }
    
        private void registerAlias(BeanDefinitionRegistry registry, Map attributes) {
          ...
          registry.registerAlias(name, alias);
        }
    }
    

提交回复
热议问题