2015-07-21 60 views
0

我遇到了這個示例代碼,用於實現具有JAXB數據綁定的JAX-RS。什麼是非常簡單的:您使用XML文件(客戶數據)執行POST REST請求,該文件創建客戶並將其存儲到customerDB MAP表中。然後,檢索與GET請求的客戶:JAX-RS和JAXB - 持久性配置

@Path("/customers") public class CustomerResource { private Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>(); private AtomicInteger idCounter = new AtomicInteger(); public CustomerResource() { } @POST @Consumes("application/xml") public Response createCustomer(Customer customer) { //customer.setId(idCounter.incrementAndGet()); customerDB.put(customer.getId(), customer); System.out.println("Created customer " + customer.getId() + " - " + customer.getFirstName()); System.out.println(customerDB.size()); return Response.created(URI.create("/customers/" + customer.getId())).build(); } @GET @Path("{id}") @Produces("application/xml") public Customer getCustomer(@PathParam("id") int id) { Customer customer = customerDB.get(id); if (customer == null) { System.out.println("Customer " + id + " not found"); throw new WebApplicationException(Response.Status.NOT_FOUND); } return customer; }

客戶是在爲CustomerDB地圖的確創建的,但是當你想要得到它,你有一個空的,如果你檢查爲CustomerDB的大小是0.我很驚訝這個代碼示例在一本知名品牌的書中提供不起作用。有什麼明顯的錯誤嗎? 非常感謝您的幫助。

回答

0

資源類是默認的請求範圍,意思是爲每個請求創建一個新的範圍。在你的情況下,因爲你希望數據庫持久化,你只需要一個單一的實例爲整個應用程序。如果您將資源類註冊爲實例,則會使其成爲單身人士。或者根據您使用的實施方式,您可能只需使用@Singleton對其進行註釋即可。

+0

感謝peeskillet的提示 - 使用@Singleton解決了它。但是,將該類作爲一個實例註冊會很好奇。 – Christian68

+0

如果這是Bill Burke的JAX-RS書(它看起來像(我已經閱讀過),那麼應用程序配置中應該有一章或一節,其中應用程序的子類被使用。在本書中,作者實際上將類註冊爲所有示例的一個實例,它是通過將實例添加到在重載的getSingletons()方法中返回的'Set'來完成的。所有示例都在[resteasy distribution]中。 http://sourceforge.net/projects/resteasy/files/Resteasy%20JAX-RS/)。所有示例都在oreilly-workbook目錄中。 –

+0

確實很棒! – Christian68