Wednesday, 1 November 2017

Spring Annotations

       In this post, we can learn some important Annotations used in the Spring framework.  The following are the main Annotations which are used in the Spring ,

1) @Controller


             This @Controller annotation marks a class as Spring Web MVC Controller. It too is a @Component specialization, so beans marked with it are automatically imported into the IOC container.  When you add the @Controller annotation to a class, you can use another annotation i.e @RequestMapping, to map URL's to instance methods of class.

  
 
    @Controller
    public class ControllerEx {
        .......
        ...//some code here    
    }

2) @Service

       Annotate all your service classes with @Service. All your business logic should be in Service classes.
 
 
    @Service
    public class MyService extends MasterService {
        .......
        ...//some code here    
    }

This annotation is also specialization of component annotation.  It doesn't currently provide the any additional behavior over the @Component annotation, but it's good idea to use @Service over @Component in service layer classes because it specifies intent better.


3) @Repository

          Annotate All your  DAO classes with @Repository. All your database access logic should be in DAO classes.  This annotation makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.
 
    @Repository
    public class MyRepository extends MasterRepository {
        .......
        ...//some code here    
    }

4) @Component

         Annotate other components with @Component, for example REST Resource classes.

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

@Component is a generic stereotype for any Spring managed component. @Controller, @Service and @Repository are Specializations of @Component for specific use cases.
@Component in Spring

5) @RequestMapping


       @RequestMapping annotation is used to map URL's onto an entire class or particular handler method. Typically the class-level annotation maps a specific request path onto a form controller, with additional method level annotations narrowing the primary mapping.


  @Controller
  @RequestMapping("/login")
  public class MappingEx {
       .....
       ..//some code here
  }
   

6) @PathVariable            

         You can use the @PathVariable Spring annotation on a method argument to bind it to the value of a URI template variable.
         Suppose you write a url to fetch some order you can say,

         www.mydomain.com/order/123
 
   where 123 is orderId.
 So now the URL you will use in Spring Controller would look like

       /order/{orderId}
 
 
  Now orderId can be declared as PathVariable as follows,

@Controller
@RequestMapping("order")
public class OrderController {
 
     @Autowired
     private OrderService orderService;
     
     @RequestMapping("{orderId}")
     public String getOrder(@PathVariable String orderId) {
             //call service layer n get details
            //
     }
 }


7) @RequestParam

You can bind request parameters to method variables using Spring annotation @RequestParam.
 
@Controller
@RequestMapping("/company")
public class CompanyController {

     @Autowired
     private CompanyService companyService;

     @RequestMapping("/companyList")
     public String listCompanies(Map<String, Object> map, 
     @RequestParam int pageNum) {
           map.put("pageNum", pageNum);
           map.put("companyList",companyService.listCompanies(pageNum));
           return "companyList";
     }
}


8) @Autowired

Let Spring auto-wire other beans into your classes using @Autowired annotation.


@Service
public class MyService extends MasterService {

     @Autowired
     private CompanyService companyService;
       
          ......do some logic
     
     }
}

              Spring beans can be wired by name or by type.  
  • @Autowire by default is a type driven injection. @Qualifier spring annotation can be used to further fine-tune autowiring. 
  • @Resource (javax.annotation.Resource) annotation can be used for wiring by name. 
          Beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.


9) @Qualifier

         The  @Qualifier is one of the autowiring property in spring. If dependency class is configured for more than once in spring configuration file, the IOC container will throw the exception for bean ambiguity.  In order to resolve the ambiguity, we can use @Qualifier along with @Autowired annotation.
Example,

public class Book {

     @Autowired
     @Qualifier("author2")
     private Author author;
 
     public void setAuthor(Author author){
          this.author = author
     }
}

Xml Configuration,
 
<bean id="author" class="com.adnblog.Author">
        <property name="name" value="ADNBLOG" />
</bean>
<bean id="author2" class="com.adnblog.Author">
        <property name="name" value="Example" />
</bean>


10) @Transactional


  There are types of the Transaction Management in Spring, Declarative and Programmatic . @Transactional annotation is using to manage the declarative transaction.
 
@Service
public class MyService implements MasterService {

     @Autowired
     private AddressDAO addressDAO;

     @Transactional
     public Company getAddress() {

           String address = addressDAO.getAddress();
           return address;
     }
  ...
}
 

The default @Transactional settings are as follows:
  • Propagation setting is PROPAGATION_REQUIRED.
  • Isolation level is ISOLATION_DEFAULT.
  • Transaction is read/write.
  • Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
  • Any RuntimeException triggers rollback, and any checked Exception does not.
These default settings can be changed using various properties of the @Transactional spring annotation.


11) @ModelAttribute

          An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually. 
 
@Controller
@RequestMapping("/company")
public class CompanyController {

      @Autowired
      private CompanyService companyService;

      @RequestMapping("/add")
      public String saveNewCompany(@ModelAttribute Company company) {

            companyService.add(company);
            return "redirect:" + company.getName();
      }
...
}
  


Related Post :--
Spring MVC with Hibernate CRUD Example  
Spring Annotations  
What is dependency Injection in Spring ? give me types and advantages with examples  
What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext

No comments:

Post a Comment