Home > AI > Backend > SpringBoot >

SpringBoot REST Example

Product.java
ProductService.java
ProductServiceImp.java
ProductController.javaExpose REST API

Product.java

@Data
public class Product {
    private String id;
    private String name;
}

ProductController.java

@RestController
public class ProductController {
    @Autowired
    ProductService productService;

    @RequestMapping(value = "/products")
    public ResponseEntity<Object> getProduct() {
        return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK);
    }
    @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Object>
    updateProduct(@PathVariable("id") String id, @RequestBody Product product) {

        productService.update(id, product);
        return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
    }
    @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        productService.deletet(id);
        return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
    }
    @RequestMapping(value = "/products", method = RequestMethod.POST)
    public ResponseEntity<Object> createProduct(@RequestBody Product product) {
        productService.create(product);
        return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
    }
}

ProductService.java

public interface ProductService {
    public abstract void create(Product product);
    public abstract void update(String id, Product product);
    public abstract void deletet(String id);
    public abstract Collection<Product> getProducts();
}

ProductServiceImp.java

@Service
public class ProductServiceImp implements ProductService {
    private static Map<String, Product> productRepo = new HashMap<>();

    static {
        Product honey = new Product();
        honey.setId("1");
        honey.setName("Honey");
        productRepo.put(honey.getId(), honey);

        Product almond = new Product();
        almond.setId("2");
        almond.setName("Almond");
        productRepo.put(almond.getId(), almond);
    }

    @Override
    public void create(Product product) {
        productRepo.put(product.getId(), product);
    }
    @Override
    public void update(String id, Product product) {
        productRepo.remove(id);
        product.setId(id);
        productRepo.put(id, product);
    }
    @Override
    public void deletet(String id) {
        productRepo.remove(id);

    }
    @Override
    public Collection<Product> getProducts() {
        return productRepo.values();
    }
}

Leave a Reply