Different annotation in Spring framework are @Controller, @Service, @Repository, @Component. Spring is a one of the most popular application framework in Java. User communities of Spring framework is very wide and very huge.
1. Annotation in Spring Framework
There are different annotations 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 Name | Description |
@Controller | This 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. |
@Service | used to annotate Service implementation class. |
@Repository | used for DAO(Data Access Object) class to wrap all SQLException into DataAccessException |
@Component | this 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. @Service example
code snippet of @RestController
@Service("customerService") public class CustomerServiceImpl implements CustomerService{ @Autowired private CustomerDao customerDao; -- }
5. @Repository example
code snippet of @Repository
@Repository("customerDao") public class CustomerDaoImpl implements CustomerDao { -- // some methods }
6. @RequestMapping example
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. @Autowired example
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 }
You can visit Java Spring framework for more in depth.