Java Annotations

 Java annotations—annotations automatically generate the code necessary for classes that use them to seamlessly connect within specific frameworks.

REST Annotations

@XmlRootElement : -
When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

Usage: - The @XmlRootElement annotation can be used with the following program elements:

  • a top level class
  • an enum type
@Controller:-
This annotation indicates that a particular class serves as a controller. The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.  This is easily achieved by using the spring-context schema.

@Controller annotation in spring provides a feature of auto detection. To enable auto detection of such annotated controllers, we have to add “component-scan” in spring-context and needs to provide the base-package name or controller class package name.

 
@RequestMapping :-

This annotation is used to map a web-request to a specific class or method in controller which will handle the corresponding request.  We can apply this annotation for both at class level and method level. In class level we need to map the URL of the web-request (http request) and in method level we can map url or we can also map HTTP request methods. Example:-

@RequestMapping(method = RequestMethod.GET, value = "/getEmployees")

@RequestBody :-
This annotation indicates that a method parameter should be bound to the value of the HTTP request body.

@RequestMapping(method = RequestMethod.POST, value = "/saveEmployee")

      public ModelAndView saveEmployeeInDB(@RequestBody String body) {



            Source source = new StreamSource(new StringReader(body));

            EmpBean e = (EmpBean) jaxb2Mashaller.unmarshal(source);

            System.out.println("the val from addEmployee-" + e.toString());

            employeeDS.saveEmployee(e);

            return new ModelAndView(XML_VIEW_NAME, "emp", e);

      }



Here we are converting the request body to the method argument by using an HttpMessageConverter. HttpMessageConverter is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body. DispatcherServlet supports annotation based processing using the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter.
In Spring 3.0 the AnnotationMethodHandlerAdapter is extended to support the @RequestBody and has the following HttpMessageConverters registered by default:

·         ByteArrayHttpMessageConverter converts byte arrays.

·         StringHttpMessageConverter converts strings.

·         FormHttpMessageConverter converts form data to/from a MultiValueMap.

·         SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.

·         MarshallingHttpMessageConverter converts to/from an object using the org.springframework.oxm package.
Note: - Reference from springsource.org

@PathVariable: -
In Spring MVC we can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable.

@RequestMapping(method = RequestMethod.DELETE, value = "/removeEmployee/{id}")

      public ModelAndView removeEmployeeFromDB(@PathVariable String id) {



            employeeDS.removeEmployee(Long.parseLong(id));

            List employees = employeeDS.getAllAfterDelete();

            EmpListBean list = new EmpListBean(employees);

            return new ModelAndView(XML_VIEW_NAME, "empBeanList", list);

      }

This will extract the part of the URL represented by {id}, and bind it to the id method parameter, e.g. taken as a string.
Java 5 enumeration of HTTP request methods. Intended for use with the RequestMapping.method () attribute of the RequestMapping  annotation.  Note that, by default, DispatcherServlet supports GET, HEAD, POST, PUT and DELETE only.

contextConfigLocation: -(Note :- This is a parameter(init/context), not annotation)
This init-param is required by DispatcherServlet. Using this parameter, we can change the name of Spring’s web context file and also we can change its(Spring’s web context file) location.


    contextConfigLocation

   

                                                /WEB-INF/restWebServiceWithCRUDOperations-context.xml

                               

 



Note: - contextConfigLocation parameter will call setContextConfigLocation method on DispatcherServlet and overrides default spring context config file. It is also possible to add multiple locations separated by any number of commas and space.


        contextConfigLocation

        /WEB-INF/spring-bean.xml, /WEB-INF/spring-bean-ds.xml, /WEB-INF/spring-bean-service.xml


@Consumes
This annotation works together with @POST and @PUT. It tells the framework to which method to delegate the incoming request.


@Produces

This annotation works with @GET, @POST, and @PUT. It lets the framework know what type of representation to send back to the client.


 


JAX-RS provides some annotations to aid in mapping a resource class (a POJO) as a web resource. The annotations include:

In addition, it provides further annotations to method parameters to pull information out of the request. All the @*Param annotations take a key of some form which is used to look up the value required.

  • @PathParam binds the method parameter to a path segment.
  • @QueryParam binds the method parameter to the value of an HTTP query parameter.
  • @MatrixParam binds the method parameter to the value of an HTTP matrix parameter.
  • @HeaderParam binds the method parameter to an HTTP header value.
  • @CookieParam binds the method parameter to a cookie value.
  • @FormParam binds the method parameter to a form value.
  • @DefaultValue specifies a default value for the above bindings when the key is not found.
  • @Context returns the entire context of the object.(for example @Context HttpServletRequest request)

Java Programming Overview

-If you do not provide an explicit call to super with arguments,the compiler provides a call to the super with no arguments,which results in calling a no-arguments constructor of the superclass.

-If you don't provide a no-argument constructor,the compiler makes call to the default no-argument constructor,which it provides itself.This will happen only if you have not defined any other constructor for the class;otherwise ,the compiler throws an error.

-An inherited class inherits all the fields and methods of its base class,except for its constructors.The constructor are strictly used by that base class only.

-The general rule is that if you want to detect an object type in an inheritance hierarchy,start with lowermost subclass and then move up the hierarchy to the base class.
example ;while using the instanceof operator .

-Whenever you create the subclass ,its parent class object is automatically created.

-With the extend keyword ,the subclass will be able to inherit all the properties of the superclass except the private properties.

-If you provide a constructor of your own-either no-argument one or one with arguments in the class definition-the compiler will not provide a default constructor.

-In string class--Clone method perform shallow copy and not deep copy.A shallow copy copies only the "surface' portion of an object.The actual object consists of this"surface",plus the all the objects are pointing to and so on.Copying entire web of objects is called a deep copy.

-A call to the this constructor must be the first statement int he implementation of the constructor.It cannot appear anywhere else.Therefore,you can have only one call to this,which must be first statement in the method body.If you call this ,you cannot call super because super cannot appear anywhere else other than the first statement.

-The overloading method differs by the number of the parameters or the  order of the parameters.

-The default implementation of the toString method returns an object reference.Many time developers override this method to print the object's state int the desired format.

-The first statement int he constructor may be call to to super or this.We use super to call the superclass constructor and use this to call some other class constructor defined within the same class.

-The final keyword can be used on class,a method or a variable.In general the use of final keyword restricts the further extensions or modifications.

-JVM creates all string literal objects in a dedicated memory pool and allocates the same reference to all strings having the same value.Therefore making the string class final makes sense so that java creators have ultimate control over the memory allocation used by the String type variables.

-If you do not want the subclass override your method implementation,you mark the method final.

-Because the private and static methods cannot be overridden in a subclass,they are always implicitly final.

-3 benefits by using final keyword
-----Explicitly preventing the overriding it in a subclass.(not to allow wait and notify methods system level methods that implement core language capabilities to modify from the Object class.)

-----final tells the compiler that a call to this method ,dynamic binding is not necessary,which potentially results in a slightly more efficient code.Static binding(compile time resolution) is more efficient than dynamic binding(runtime resolution of method call).

----marking a method final allows compile to turn any call tot hat method into an inline call.By which compiler will just replace the call with the actual method body avoiding all the overheads of storing method details on stack and popping out.

-A blank final variable must be initialized in a constructor because it is called only once during the object life cycle.If the final keyword is initialized in a constructor,it must be initialized in all overloaded constructors.

-If a final variable holds reference to an object,the reference must remain constant,not the object. We can change the object's state by invoking mutator methods on it.

-A final variable of the class type cannot refer to any object other than the object reference to which it has been set.





-

ref:Java Programming book by Poornachandra Sarang

-