Friday 23 September 2016

Spring and Restful WebServices Annotations

Spring Annotations


@RestController : Used to  load the controller in Spring.

@PropertySource : To load the Property files in the Service.
Ex : @PropertySource("classpath:service.properties")

@RequestMapping : To map the Request From Controller to Service.
Ex : @RequestMapping(value="/modulename.resourcename.methodname",method=RequestMethod.GET)

@RequestBody : Used to map the request object (POJO) into the request.

@Requestparam : used to send the request parameters into the service.

@Component : Simillar to @ Service. Provide the services in Spring.

@Transactional : Used to do the Transactions with DAO. Will Write these annotation in Service only.
Having below transaction types :
TxType : REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, MANDATORY, NEVER

@Repository : Used to connect the Database tables and retrive from DB.

RestFul WebServices :


@Path : Will Find the path for providing WebServcies and Services.

@GET : Used to get the information.

@Produces : Used to Produce the formats like JSON, XML, STRING,OCTETSTREAM etc.

@Consumes :  Used to Consume the formats like JSON, XML, STRING,OCTETSTREAM etc.

@POST : Used to post the information into service.

@DELETE : Used to delete the info in service.

@PUT : Used to update the info.

@QueryParam : used to send the non mandatory fields into the service.

@PathParam : Used to send the mandatory fields into the service.

@Cacheable : Used to cache the information.


Different Types of RestTemplate Calls : 

Method 1: 

HttpHeaders headers = new HttpHeaders();
        headers.add("user-id", userId);
        headers.add("Content-Type", Constants.APPLICATION_JSON);
String serviceUrl = "http://localhost:8080/testapi";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(serviceUrl);
        builder.queryParam("name", name);

// http://localhost:8080/testapi?name=lokesh;

HttpEntity<String> requestEntity = new HttpEntity<>(headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(builder.toUriString(),
                    HttpMethod.GET, requestEntity, String.class);


Method 2:

RequestEntity<RequestObject> requesetEntity = null;
requesetEntity = RequestEntity.post(new URI(serviceUrl)).accept(MediaType.APPLICATION_JSON)
                    .header("user-id", userId).header("Authorization", accessToken).body(requestData);

            ResponseEntity<String> response = restTemplate.exchange(requesetEntity, String.class);



JSON Conversion : 

JsonObject bodyObj = (JsonObject) jsonParser.parse(response.getBody());
        if (bodyObj != null && bodyObj.get("data") != null) {
            studentResponse= gson.fromJson(bodyObj.get("data").toString(), StudentResponse.class);

        }


SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...