2016-10-02 139 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