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"; 
}