The annotation "@Added" is disallowed for this location, when using custom annotation with events in CDI

16,566

What's the definition of your qualifier annotations @Added and @Removed?

You're probably missing the PARAMETER entry in the @Target list:

@Target({ TYPE, METHOD, PARAMETER, FIELD })
Share:
16,566
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin about 2 years

    When using a custom qualifier near the @Observes qualifier to catch an event I have this compilation error.

    All the classes are in the same package so the problem is not the import statements. I already checked that.

    @Inject
    private Logger logger;
    List<Book> inventory = new ArrayList<>();
    
    public void addBook(@Observes @Added Book book) {
        logger.warning("adding book" + book.getTitle());
        inventory.add(book);
    }
    
    public void removeBook(@Observes @Removed Book book) {
        logger.warning("remove book");
    }
    

    So, this line: public void addBook(@Observes @Added Book book) {

    and this like: public void removeBook(@Observes @Removed Book book) {

    are marked with the following error: The annotation @Added (@Removed) is not allowed for this location.

    And here is the code that defines the methods addBook and removeBook. Here there's no problem.

    @Inject
    @Added
    private Event<Book> bookAddedEvent;
    
    @Inject
    @Removed
    private Event<Book> bookRemovedEvent;
    
    public Book createBook(String title, float price, String description) {
        Book book = new Book(title, price, description);
        book.setNumber(numberGenerator.generateNumber());
    
        bookAddedEvent.fire(book);
        return book;
    }
    
    public void deleteBook(Book book) {
        bookRemovedEvent.fire(book);
    }