Different Annotations in Spring framework

Connect with

Spring Framework
Spring is a one of the most popular Application Framework in java. the user communities of Spring framework are wide and huge. you can find different annotation used in Spring application framework: @Controller, @Service, @Repository, @Component

1. Different Annotation used in Spring Framework

There are different annotation used in Spring Application Framework , here are some key annotations used in Spring. If you novice in Spring Framework you can view my another post , Spring Restful Webservice example with Maven and Tomcat.

Annotation NameDescription
@ControllerThis is used to tell to spring container that this class is used as Controller
@RestController This is used to tell to spring container that this class is used as Rest Controller (Spring Restful Webservice controller)\, not returns any view in this class method.
@Serviceused to annotate Service implementation class.
@Repositoryused for DAO(Data Access Object) class to wrap all SQLException into DataAccessException
@Componentthis is super class of @Controller, @Service, @Repository. its used basically in utility sort of class like property Editor, validator, etc.
@Autowired
This is used to inject the bean by the spring container.

2. example of @Controller

code snippet of @Controller

@Controller
@RequestMapping(value="/customer")
public class CustomerController { 
 ...
// some methods
}

3. example of @RestController

code snippet of @RestController

@RestController
@RequestMapping(value="/customer")
public class CustomerController { 

--
}

4. example of @Service

code snippet of @RestController

@Service("customerService")
public class CustomerServiceImpl implements CustomerService{

 @Autowired
 private CustomerDao customerDao;
--
}

5. example of @Repository

code snippet of @Repository

@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {

--
// some methods
}

6. example of @RequestMapping

code snippet of @RequestMapping

@RestController
@RequestMapping(value="/customer")
public class CustomerController {


/**
  * @return
  */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public ResponseEntity 	 	 	 	 	> getCustomerListHandler() {
  List customerList = null;
  HttpStatus status = HttpStatus.OK;
  try {
   customerList = customerService.getCustomers();
   if (customerList == null) {
    
   }
  } catch (Exception e) {
   status = HttpStatus.BAD_REQUEST;
  }

  return new ResponseEntity 	 	 	 	 	>(customerList, status);
 }

}

7. example of @Autowired

code snippet of @Autowired

@Controller
@RequestMapping(value="/customer")
public class CustomerController {

// create the reference of CustomerService, 
// Spring container inject it implementation bean into it.
 @Autowired
 private CustomerService customerService;

// some methods below
}

Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *