java 当对 CDI 中的事件使用自定义注释时,此位置不允许使用注释“@Added”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28231004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:12:51  来源:igfitidea点击:

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

javaeventscdi

提问by Gica

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

在@Observes 限定符附近使用自定义限定符来捕获事件时,我遇到了此编译错误。

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

所以,这一行: public void addBook(@Observes @Added Book book) {

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

就像这样: public void removeBook(@Observes @Removed Book book) {

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

标有以下错误:此位置不允许使用注释@Added (@Removed)。

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

这是定义 addBook 和 removeBook 方法的代码。这里没有问题。

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

回答by Harald Wellmann

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

什么是你的预选赛注释的定义@Added@Removed

You're probably missing the PARAMETERentry in the @Targetlist:

您可能遗漏PARAMETER@Target列表中的条目:

@Target({ TYPE, METHOD, PARAMETER, FIELD })