Hỏi về Restful Service sử dụng Jersey

Bác nào biết về inject trong ResourceConfig() của restful không cho mình hỏi về Inject bằng @Context annotation với nhỉ!

Vấn đề của mình như sau: Inject class, lớp được lớp không. Không hiểu nổi nó hoạt động sao nữa trong khi scan các packages chứa class liên quan hoặc đưa về chung package cũng vậy. Chẳng biết giải quyết như nào nữa.

  • Code chạy server
public HttpServer startServer(final String baseUri) throws URISyntaxException {
    ResourceConfig rc = new ResourceConfig()
            // scan packages
            .packages(true, "mta/edu")
            // regis object to use, usage with @Context annotation
            .register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(new BookRepository())
                            .to(BookRepository.class);
                    bind(new ListenBookService())
                            .to(ListenBookService.class);
                    bind(MoreExecutors.listeningDecorator
                            (Executors.newFixedThreadPool(10)))
                            .to(ListeningExecutorService.class);
                }
            });

    URI uri = new URI(baseUri);
    HttpServer createHttpServer = GrizzlyHttpServerFactory.createHttpServer(uri, rc);
    return createHttpServer;
}

/**
 * 
 * @param args
 * @throws URISyntaxException
 * @throws IOException
 */
public static void main(String[] args) throws URISyntaxException, IOException {
    MyMain myMain = new MyMain();
    final String baseUri = "http://localhost:8080/hihe/";
    System.out.println(String.format("WASL in %sapplication.wadl", baseUri));
    HttpServer startServer = myMain.startServer(baseUri);
    System.in.read();
    startServer.stop();
}
  • Đây là code của mình đối với lớp được

Inject

@Context
BookRepository bookRepository;
@Context
ListenBookService listenBookService;
@Context
ListeningExecutorService listeningExecutorService;

Request

@Path("/asyn/books/{id}")
@GET
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void getIdAsyn(@PathParam("id") int id,
                          @Suspended final AsyncResponse asyncResponse) {
    if (listenBookService != null) {
        System.out.println(listenBookService.getClass().getCanonicalName());
    }
    if (listeningExecutorService != null) {
        System.out.println(listeningExecutorService.getClass().getSimpleName());
    }
    if (bookRepository != null) {
        System.out.println(bookRepository.getBooks().size());
    }

    ListenableFuture<BookbookIdAsyn = listenBookService.getBookIdAsyn(id);
    Futures.addCallback(bookIdAsyn, new FutureCallback<Book>() {
        @Override
        public void onSuccess(@Nullable Book book) {
            asyncResponse.resume(book);
        }

        @Override
        public void onFailure(Throwable throwable) {
            asyncResponse.resume(throwable);
        }
    }, listeningExecutorService);
}

Lớp không được

public class ListenBookService {
    @Context
    ListeningExecutorService listeningExecutorService;
    @Context
    BookRepository bookRepository;


    public ListenableFuture<BookgetBookIdAsyn(int id) {
        if (bookRepository != null) {
            System.out.println("Not null!!");
        }
        Book book = bookRepository.getBook(id);

        ListenableFuture<Booksubmit = listeningExecutorService.submit(new Callable<Book>() {
            @Override
            public Book call() throws Exception {
                return book;
            }
        });

        return submit;
    }
}

Bạn tự new intance thì tất nhiên không có DI rồi

Là sao anh, em không tự khởi tạo thực thể ở đâu cả? ngoại trừ main :smiley:, mà hình như em mò ra là cái DI của Jersey chỉ làm việc khi gọi tới service mà nó cung cấp, ngoài ra thì không. Nên em nghĩ thay cái đó bằng @Inject. Nhưng liệu có cách nào để inject bên trong class mà dùng @Context không nhỉ, vì em thấy nó inject khá tiện :slight_smile:. Còn inject của mấy ông kia thì phải khai báo cả đống thư viện trong mvn :smile:

Thế đây là gì hả bạn

Cái đó giống @Produces trong @Inject anh ạ. Không có cái đó thì sao mà có thực thể tương tác chứ :frowning:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?