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.我很驚訝這個代碼示例在一本知名品牌的書中提供不起作用。有什麼明顯的錯誤嗎? 非常感謝您的幫助。
感謝peeskillet的提示 - 使用@Singleton解決了它。但是,將該類作爲一個實例註冊會很好奇。 – Christian68
如果這是Bill Burke的JAX-RS書(它看起來像(我已經閱讀過),那麼應用程序配置中應該有一章或一節,其中應用程序的子類被使用。在本書中,作者實際上將類註冊爲所有示例的一個實例,它是通過將實例添加到在重載的getSingletons()方法中返回的'Set'來完成的。所有示例都在[resteasy distribution]中。 http://sourceforge.net/projects/resteasy/files/Resteasy%20JAX-RS/)。所有示例都在oreilly-workbook目錄中。 –
確實很棒! – Christian68