首页 > 解决方案 > Injecting Services in Entity Listener ...?

问题描述

Is it by any means possible to @Inject a Service-Bean (say a session bean) into an entity Listener?

Consider the following scenario as an example

Entity:

@Entity
@EntityListeners(BookListener.class)
public class Book {
    // fields, getters & setters
}

Utility class:

@Singleton
public class BookUtil {

    private BookRepository bookRepo;
    private List<Book> bookList;

    @Inject
    public BookUtil(BookRepository bookRepo){
        this.bookRepo = bookRepo;
        this.bookList = this.bookRepo.findAll();
    }

    public void refreshBooks(){
        this.bookList = this.bookRepo.findAll();
    }

}

Listener:

public class BookListener {

    @Inject
    BookUtil bookUtil // --> CAN THIS BE ACHIEVED?

    @PostPersist
    private void refreshCache(Book b){
        bookUtil.refreshBooks();
    }
}

I tried out several things I could think of but none of them successfully injected an instance of BookUtil. I could manually instantiate it, which works. But I prefer injection as then the BookRepository(inside the BookUtil) would also be injected, without me having to worry about it

标签: jpacallbackcdientitylisteners

解决方案


推荐阅读