我已经创建了新的自定义注释
@MyCustomAnnotation
:
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD})
@Retention(RUNTIME)
public @interface MyCustomAnnotation {
}
我在组件和 bean 上应用了该注释。这是代码,
@MyCustomAnnotation
@Component
public class CoreBusinessLogicHandler implements GenericHandler<BusinessFile> {
// some business logic
}
还有
@Configuration
public class BusinessConfig {
@Autowired
private CoreIntegrationComponent coreIntegrationComponent;
@MyCustomAnnotation
@Bean(name = INCOMING_PROCESS_CHANNEL)
public MessageChannel incomingProcessChannel() {
return coreIntegrationComponent.amqpChannel(INCOMING_PROCESS_CHANNEL);
}
//some other configurations
}
现在我想要所有带有
@MyCustomAnnotation
注释的 beans。这是代码:
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 CoreBusinessLogicHandler Only.
}
}
我的问题是为什么我没有得到名称为“INCOMING_PROCESS_CHANNEL”的 Bean,因为它有
@MyCustomAnnotation
?如果我想获得名称为“INCOMING_PROCESS_CHANNEL”的 bean,我应该做什么代码更改?
发生这种情况是因为您的 bean 没有收到此注释,因为您已将其放置在“bean 定义配置”上。所以它是可用的,但只能通过 BeanFactory 和 beanDefinitions 来实现。您可以将注释放在 bean 类上,也可以编写一个自定义方法来使用 bean 工厂进行搜索。
请参阅此处已接受的答案。
您必须使用 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";
}