2016-10-02 138 views
0

有没有一种方法可以在每个使用给定字符串的包和子包中使用@Component注释的每个bean的前缀?如何在Spring中使用常量字符串将包中的每个bean id(包含子包)加上前缀?

说,我们有这个bean,例如:

package com.example.foo; 

@Component 
class MyBean {} 

我想在foo所有豆与foo前缀,从而自动地(由成分扫描)产生的豆ID已fooMyBean(优选,大写字母'M')或foo-myBean(而不是默认的myBean)。 (前缀是在某处定义的字符串,不能自动从包名中派生出来。)

或者,我可以通过使用自定义注释(如@FooComponent)来实现此目的吗? (How?;-))

+0

@Component( “fooMyBean”)http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html – jmw5598

+0

好吧,我希望的是稍微更自动化/集中的方法...;) – Christian

回答

1

Spring使用BeanNameGenerator策略来生成bean名称。特别是,AnnotationBeanNameGenerator是使用首字母小写的策略为@Component类别生成名称的类别。

您可以实施自己的BeanNameGenerator并通过检查传递的BeanDefinition来应用自定义策略。

如果您使用的是Spring Boot,则可以在SpringApplicationBuilder中完成。

@SpringBootApplication 
public class DemoApplication { 

    public static class CustomGenerator extends AnnotationBeanNameGenerator { 

     @Override 
     public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { 
      /** 
       * access bean annotations or package ... 
       */ 
      return super.generateBeanName(definition, registry); 
     } 
    } 

    public static void main(String[] args) { 
     new SpringApplicationBuilder(DemoApplication.class) 
       .beanNameGenerator(new CustomGenerator()) 
       .run(args); 
    } 
} 
+0

那么,我将如何注册我的新BeanNameGenerator使用普通的Spring(而不是SpringBoot)和b)只调用它的自定义注释@ @ MyComponent注释的豆,说? (我不希望我的命名策略影响我导入的库中的bean,因为它们可能通过id引用它们的bean) – Christian

+0

我已经设置了我的注释@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME )@Documented @Component public @interface MyC {String value()default“”; }'和我的xml config:''现在我为每个使用'@ MyC'注解的类获得2个bean:'( – Christian

+0

删除'@ Component'注释'@ MyC'修复了double-instantiation的问题,但是现在我不能再在'AnnotationBeanNameGenerator'中的'@MyC(“foo”)处传递一个明确的值“foo” – Christian