Spring Annotations




Context Configuration Annotations::-----

@ContextConfiguration loads an ApplicationContext for Spring integration test. @ContextConfiguration can load ApplicationContext using XML resource or the JavaConfig annotated with @Configuration. The @ContextConfiguration annotation can also load a component annotated with @Component@Service@Repository etc. We can also load classes annotated with javax.inject.

@ContextConfiguration annotation has following elements.
classes: The classes annotated with @Configuration are assigned to load ApplicationContext.

inheritInitializers: A Boolean value to decide whether context initializers from test super classes should be inherited or not. Default is true.

inheritLocations: A Boolean value to decide whether resource locations or annotated classes from test super classes should be inherited or not. Default value is true.

initialisers: We specify application context initializer classes that initialize ConfigurableApplicationContext.

loader: We specify our ContextLoader or SmartContextLoader class to load ApplicationContext.

locations: We specify resource locations to load ApplicationContext.
name: Name of context hierarchy level represented by this configuration.
value: It is the alias for locations element.






Core Spring Annotations ::---


These annotations are used by Spring to guide creation and injection of beans.
                            
@Autowired        
This   annotation is used  in  lieu  of   xml base   autowiring    by the type , Constructor  . Declares a constructor, field, setter method, or configuration method to be autowired by type. Items annotated with @Autowired do not have to be public.
 For @Autowired annotation to work, we also need to enable annotation based configuration in spring bean configuration file. This can be done by context:annotation-config element or by defining a bean of type
 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.




@Configurable                                             

Used with <context:springconfigured> to declare types whose properties should be injected, even if they are not instantiated by Spring. Typically used to inject the properties of domain objects.


@Order               

Type, Method, Field                                     

The @Order annotation defines the sorting order of an annotated component or bean.
It has an optional value argument which determines the order of the component; the default value is Ordered.LOWEST_PRECEDENCE. This marks that the component has the lowest priority among all other ordered components.
The @Order annotation defines the sorting order of an annotated component or bean.
It has an optional value argument which determines the order of the component; the default value is Ordered.LOWEST_PRECEDENCE. This marks that the component has the lowest priority among all other ordered components.
   springframework.core.Ordered interface.




  
@Qualifier          

Field, Parameter, Type, Annotation Type   

This annotation is used to avoid conflicts in bean mapping and we need to provide the bean name that will be used for autowiring. This way we can avoid issues where multiple beans are defined for same type. This annotation usually works with the @Autowired annotation. For constructors with multiple arguments or method with same type, we can use this annotation with the argument names in the method

@Required

The @Required annotation applies to bean property setter methods and it indicates that the affected bean property must be populated in XML configuration file at configuration time. Otherwise, the container throws a BeanInitializationException exception. Following is an example to show the use of @Required annotation.
  
    This   is   example for implementation for @required annotation


 package com.bhirkutisoft;

import org.springframework.beans.factory.annotation.Required;

public class  Employee {
   private Integer age;
   private String name;

   @Required
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
  
   @Required
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
}




MainApp   Java class
---------------------------
package com.bhirkutisoft;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {


   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
     
      Employee emp = (Employee) context.getBean("employee");
      System.out.println("Name : " + employee.getName() );
      System.out.println("Age : " + employee.getAge() );
   }
}


Bean.xml
---------------
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context = "http://www.springframework.org/schema/context"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for Employee bean -->
   <bean id = "Employee" class = "com.bhirkutisoft.Employee">
      <property name = "name" value = "Himani" />

      <!-- try without passing age and check the result -->
      <!-- property name = "age"  value = "11"-->

  </bean>

</beans>


@Scope                                              

Specifies the scope of a bean, either singleton, prototype, request, session, or some custom scope.


Stereotyping Annotations
These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration.
In addition, if a PersistenceExceptionTranslationPostProcessor is configured in Spring, any bean annotated with @Repository will have SQLExceptions thrown from its methods translated into one of Spring's unchecked DataAccessExceptions.


ANNOTATION     USE     DESCRIPTION
@Component          
 This  annotation  is use to scan the classes  automatically  to inject dependency  when
     annotation  based  configuration and classpath scaning is used.
   
   @Component
  public @interface Controller {
   
  }

@Component
public class AdressComp{
    .......
    ...//some code here   
}



@Controller            
  This annotation is used    to   declare class to handle the  request  send  by user 
 through Dispatcher servlet   and   web container.  A application can have multiple   controllers.
 Simple  example for controller

  1. package com.bhirkutisoft;  
  2. import org.springframework.stereotype.Controller;  
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. @Controller  
  5. public class HelloController {  
  6. @RequestMapping("/")  
  7.     public String display()  
  8.     {  
  9.         return "index";  
  10.     }     
  11. }  

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  3.   <display-name>SpringMVC</display-name>  
  4.    <servlet>    
  5.     <servlet-name>spring</servlet-name>    
  6.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
  7.     <load-on-startup>1</load-on-startup>      
  8. </servlet>    
  9. <servlet-mapping>    
  10.     <servlet-name>spring</servlet-name>    
  11.     <url-pattern>/</url-pattern>    
  12. </servlet-mapping>    
  13. </web-app> 

 Dispatcher servlet
   spring-servlet.xml



  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans  
  8.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.         http://www.springframework.org/schema/context  
  10.         http://www.springframework.org/schema/context/spring-context.xsd  
  11.         http://www.springframework.org/schema/mvc  
  12.         http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  13.   
  14.     <!-- Provide support for component scanning -->  
  15.     <context:component-scan base-package="com.javatpoint" />  
  16.   
  17.     <!--Provide support for conversion, formatting and validation -->  
  18.     <mvc:annotation-driven/>  
  19.   
  20. </beans>


@Repository           
@Repository   Classes annotated with this, are intended to connect with database. It can also be considered as DAO(Data Access Object) layer. This layer should be restricted to CRUD (create, retrieve, update, delete) operations only. If any manipulation is required, data should be sent be send back to @Service layer.

@Service                   
@Service  Classes annotated with this, are intended to manipulate data, that we receive from the client or fetch from the database. All the manipulation with data should be done in this layer.




Spring MVC Annotations
These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications with minimal XML configuration and without extending one of the many implementations of the Controller interface.
A
TATION                USE                DESCRIPTION
@Controller               
    As   discuss  above.

@InitBinder               
@ModelAttribute      

Parameter, Method When applied to a method, used to preload the model with the value returned from the method. When applied to a parameter, binds a model attribute to the parameter

@RequestMapping   
@RequestMapping is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.
  Simple  example of  @RequestMapping     using Rest



 RestController
@RequestMapping("/home")
public class IndexController {
    @RequestMapping(value = "/name")
 String getName(@RequestParam(value = "person", required = false)
 String personName) {
        return "Required element of request param";
    }
}

@RequestParam       
@RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.
Including form data, it also maps the request parameter to query parameter and parts in multipart requests. If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map else the map parameter is populated with all request parameter names and values.


 If  you  have  any  suggestion  , please  comment below.

.


Spring Annotations Spring  Annotations Reviewed by Mukesh Jha on 11:21 PM Rating: 5

1 comment:

  1. It’s necessary to know the varied kinds of roulette games before you get started. By contrast to the regular bets on a roulette table, a Neighbours guess permits you to guess on whole sectors on the roulette wheel. These sectors include Orphelins (à Cheval), Voisins du Zéro and Tiers du Cylindre, and each 빅카지노 of them can be adjusted by the consecutive number of neighbour pockets included in a guess. The American Roulette wheel rules include 38 pockets in complete. Respectively, the table layout options a further 'double-0' area along with the regular '0' and the opposite 36 black and pink numbers. Accordingly, the arrangement and the sequence of the numbers on the American wheel are totally different.

    ReplyDelete

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.