Gica
Gica

Reputation: 23

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

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);
}

Upvotes: 2

Views: 21531

Answers (1)

Harald Wellmann
Harald Wellmann

Reputation: 12855

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

Upvotes: 10

Related Questions