2

我創建了我新的自定義註釋@MyCustomAnnotation自定義註釋不會在Spring bean工作

@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD}) 
@Retention(RUNTIME) 
public @interface MyCustomAnnotation{ 
} 

我申請的組件和bean中的註釋。下面是代碼,

@MyCustomAnnotation 
@Component 
public class CoreBussinessLogicHandler implements GenericHandler<BussinessFile> { 
//some bussiness logic 
} 

而且

@Configuration 
public class BussinessConfig { 

    @Autowired 
    private CoreIntegrationComponent coreIntegrationComponent; 

    @MyCustomAnnotation 
    @Bean(name = INCOMING_PROCESS_CHANNEL) 
    public MessageChannel incomingProcessChannel() { 
     return coreIntegrationComponent.amqpChannel(INCOMING_PROCESS_CHANNEL); 
    } 

    //some other configurations 
} 

現在我想用@MyCustomAnnotation註釋的所有豆子。因此,這裏的代碼,

import org.springframework.context.ApplicationContext; 

@Configuration 
public class ChannelConfig { 

     @Autowired 
     private ApplicationContext applicationContext; 

     public List<MessageChannel> getRecipientChannel(CoreIntegrationComponent coreIntegrationComponent) { 

     String[] beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(MyCustomAnnotation.class); 
     //Here in output I am getting bean name for CoreBussinessLogicHandler Only. 

    } 
} 

我的問題是,爲什麼我沒有名爲「INCOMING_PROCESS_CHANNEL」越來越豆,因爲它有@MyCustomAnnotation?如果我想獲得名爲'INCOMING_PROCESS_CHANNEL'的bean,我應該做些什麼代碼更改?

回答

1

發生這種情況是因爲您的bean沒有收到此註釋,因爲您已將它放在「bean定義配置」上。所以它是可用的,但只能通過BeanFactory和beanDefinitions。您可以將註釋放在您的bean類上,也可以編寫一個自定義方法來使用bean工廠進行搜索。

查看accepted answer here

1

你必須使用AnnotationConfigApplicationContext,而不是的ApplicationContext

這裏是一個工作示例:

@SpringBootApplication 
@Configuration 
public class DemoApplication { 

    @Autowired 
    public AnnotationConfigApplicationContext ctx; 

    @Bean 
    public CommandLineRunner CommandLineRunner() { 
     return (args) -> { 
      Stream.of(ctx.getBeanNamesForAnnotation(MyCustomAnnotation.class)) 
        .map(data -> "Found Bean with name : " + data) 
        .forEach(System.out::println); 
     }; 
    } 

    public static void main(String[] args) { 
     SpringApplication.run(DemoApplication.class, args); 
    } 
} 

@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD}) 
@Retention(RetentionPolicy.RUNTIME) 
@interface MyCustomAnnotation{ 
} 

@MyCustomAnnotation 
@Component 
class Mycomponent { 
    public String str = "MyComponentString"; 
}