2

J'ai créé ma nouvelle annotation personnalisée @MyCustomAnnotationannotation personnalisée ne fonctionne pas sur printemps Beans

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

J'ai appliqué cette annotation sur le composant et le haricot. Voici le code,

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

Et

@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 
} 

Maintenant, je veux tous les haricots annotés avec @MyCustomAnnotation. Donc, voici le code,

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. 

    } 
} 

Ma question est pourquoi je ne reçois pas de haricots avec le nom « INCOMING_PROCESS_CHANNEL » comme il a @MyCustomAnnotation? Si je veux obtenir un bean avec le nom "INCOMING_PROCESS_CHANNEL", quel changement de code dois-je faire?

Répondre

1

Cela se produit car votre bean ne reçoit pas cette annotation comme vous l'avez placé sur une "configuration de définition de bean". Il est donc disponible mais uniquement via BeanFactory et beanDefinitions. Vous pouvez soit mettre l'annotation sur votre classe de bean ou écrire une méthode personnalisée qui ferait la recherche en utilisant l'usine de haricots. Voir le accepted answer here.

1

Vous devez utiliser AnnotationConfigApplicationContext au lieu de ApplicationContext

Voici un exemple de travail:

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