自定义注释不适用于Spring Beans

时间:2017-08-29 05:50:21

标签: java spring spring-mvc spring-integration spring-annotations

我创建了新的自定义注释@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,我应该做哪些代码更改?

2 个答案:

答案 0 :(得分:1)

这是因为你的bean没有收到这个注释,因为你已将它放在&#34; bean定义配置&#34;上。所以它可用,但只能通过BeanFactory和beanDefinitions。您可以将注释放在bean类上,也可以编写一个自定义方法,使用bean工厂进行搜索。

请参阅accepted answer here

答案 1 :(得分: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";
}
相关问题