Spring Annotation

Introduction

The most common annotation in Spring would include @Component, @Repository, @Service and @Controller.

@Component is the generic term for Spring Bean. @Repository, @Service and @Controller are subclass of @Component. They have specific usage in Spring Framework. @Repository represent a Spring Bean in Persistent Layer. @Service represent a Spring Bean in Service Layer.@Controller represents a Spring Bean in Presentation Layer.

@Controller

@Controller specify a Class as a Spring Bean in Presentation Layer of Spring Web MVC Framework. It would work with other annotations such as @RequestMapping, @PathVariable, @RequestParam, @MatrixVariable, @RequestHeader, @RequestPart, @SessionAttribute, @RequestAttribute, @ModelAttribute, @ResponseBody.

By default, the scope of Spring Bean annotated with @Controller is Singleton

@RequestMapping and @ResponseBody

@RequestMapping could be place above a class or a method. It would specify a request method or URL that would be handled. @ResponseBody specify the return type would be written to HTTP response body.

@Controller
public class ExampleController {

  @RequestMapping("/")
  @ResponseBody
  public String handle(){
    return "Hello World";
  }
}

@Repository

@Repository specify a class as a Spring Bean of Data Access Object (DAO) in Spring Frameowork. It provide support for DataAccessException which is a generic exception for technology-specific exception such as SQLException, HibernateException and JDOExcpetion. It provide access to DataSource through @Autowired, @Inject, @Resource, @PersistenceContext. Also,  Spring Framework would handle the transaction management in its Data Access Object annotated with @Repository.

@Service

@Service is more specific than @Component. It indicate the class as a Business Service Facade. Currently, no specific support is added @Service to make it very different from @Component.

廣告

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s