自定义注释不适用于 spring 个 Bean

Custom annotation is not working on spring Beans

我已经创建了新的自定义注释@MyCustomAnnotation

@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 注释的bean。所以这是代码,

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' 的 Bean,因为它有 @MyCustomAnnotation?如果我想获得名称为 'INCOMING_PROCESS_CHANNEL' 的 bean,我应该更改哪些代码?

发生这种情况是因为您的 bean 在将其放置在 "bean definition configuration" 上时未收到此注释。所以它是可用的,但只能通过 BeanFactory 和 beanDefinitions。您可以将注释放在 bean 上 class 或编写一个自定义方法来使用 bean 工厂进行搜索。

查看accepted answer here

您必须使用 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";
}