框架中常见的注解分析

按照注解的来源,也是分为3类
1. 内置注解 如@Override ,@Deprecated 等等
2. 第三方注解,如Hibernate, Struts等等
3. 自定义注解,如fahibernate的自定义注解

        在工作中,大部分都使用的是第三方注解。那么接下来就介绍一些常用的第三方注解如:@RequestMapping、@ResponseBody、@Autowired 、@Scope、@Controller、@Service、@Repository、@Component、@RequiresPermission等等.

  

@RequestMapping
  • requestmapping是一个用来处理请求地址映射的注解,可用于类或者方法上。
          <1>用于类上:表示类中的所有响应请求的方法都是以该地址作为父路径。
  • requestmapping有六个属性,可以分为以下三类:
<1>value、method:
     1.value : 指定请求的实际地址(可以是URI Template 模式);
默认RequestMapping("....str...")即为value的值;
复制代码
 1 @Controller
 2 @RequestMapping("/appointments")
 3 public class AppointmentsController {
 4 
 5     private AppointmentBook appointmentBook;
 6    
 7     @Autowired
 8     public AppointmentsController(AppointmentBook appointmentBook) {
 9         this.appointmentBook = appointmentBook;
10     }
11 
12     @RequestMapping(method = RequestMethod.GET)
13     public Map<String, Appointment> get() {
14         return appointmentBook.getAppointmentsForToday();
15     }
16 
17     @RequestMapping(value="/{day}", method = RequestMethod.GET)
18     public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
19         return appointmentBook.getAppointmentsForDay(day);
20     }
21 
22     @RequestMapping(value="/new", method = RequestMethod.GET)
23     public AppointmentForm getNewForm() {
24         return new AppointmentForm();
25     }
26 
27     @RequestMapping(method = RequestMethod.POST)
28     public String add(@Valid AppointmentForm appointment, BindingResult result) {
29         if (result.hasErrors()) {
30             return "appointments/new";
31         }
32         appointmentBook.addAppointment(appointment);
33         return "redirect:/appointments";
34     }
35 }
复制代码
value的uri值为以下三类:
 
A) 可以指定为普通的具体值;
 
B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);
 
C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

example B)

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  model.addAttribute("owner", owner);  
  return "displayOwner"; 
}

example C)

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:d.d.d}.{extension:.[a-z]}")
  public void handle(@PathVariable String version, @PathVariable String extension) {   
    // ...  }
}
     2.method:指定请求的method类型(GET、POST、PUT、DELETE等);
<2>consumes、produces:
     1.cousumes的样例:
     
   @Controller
        @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
         public void addPet(@RequestBody Pet pet, Model model) {   
                   // implementation omitted
          }
          方法仅处理request Content-Type为“application/json”类型的请求。
 
     2.produces的样例:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {   
    // implementation omitted
}
          方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;
<3>params、headers
1.params的样例:
复制代码
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {   
    // implementation omitted  }
}
复制代码
          仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
 
          2. headers的样例:
复制代码
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
 
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {   
    // implementation omitted  }
}
复制代码
仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;
 
<4> @RequestMapping拦截多个请求
 1 @RequestMapping(value={"dayAttendanceCount","psdayAttendanceCount"}) 
          
@RequestBody
<1>作用:
      该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;再把HttpMessageConverter返回的对象数据绑定到controller中方法的参数上。
<2>使用时机:
  1. GET、POST方式提交时,根据request header ContentType的值来判断:
  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
      2.PUT方式提交时,根据request header Content-Type的值来判断:
  •     application/x-www-form-urlencoded, 必须;
  •     multipart/form-data, 不能处理;
  •     其他格式, 必须;
说明:request的body部分的数据编码格式由header部分的Content-Type指定;
 
@ResponseBody
<1> 作用:
      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
<2> 使用时机:
      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
 
@PathVariable
当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
示例代码:[java] 
复制代码
@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping("/pets/{petId}")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted   
  }  
}  
复制代码
上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。
 
@RequestParameter
A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

示例代码:

复制代码
@Controller  
@RequestMapping("/pets")  
@SessionAttributes("pet")  
public class EditPetForm {  
    @RequestMapping(method = RequestMethod.GET)  
 public String setupForm(@RequestParam("petId") int petId, ModelMap model) {  
       Pet pet = this.clinic.loadPet(petId);  
   model.addAttribute("pet", pet);  
   return "petForm";  
   }  
复制代码
@Autowired
      Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。从而达到精简程序的目的。
 
 
@Scope
      当我们在一个ACTION类里面写很多个方法的时候(其实是一种按功能划分模块编程的思想),每个方法的返回状态可能不一样,如果ACTION中不@Scope("prototype"),有可能报找不到XXXACTION的错误!写上这个就表示每次请求都重新创建一个ACTION,与SINGALON对应,俗称“多例”。
 
@Component 和 @Controller,@Service,@Repository
1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
  @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。 
下面写这个是引入component的扫描组件 
<context:component-scan base-package=”com.mmnc”>    
      在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。 Spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,我们需要打开以下配置信息: 
Java代码: 
复制代码
 <?xml version="1.0" encoding="UTF-8" ?> <beansxmlns="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-2.5.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd" 
 > <context:component-scan base-package=”com.eric.spring”>   
 </beans>   
复制代码
        其中base-package为需要扫描的包(含所有子包) @Service用于标注业务层组件,@Controller用于标注控制层组件(如struts中的action),@Repository用于标注数据访问组件,即DAO组件,而@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。   
复制代码
@Service
public class VentorServiceImpl implements iVentorService{   
 } 
@Repository
public class VentorDaoImpl implements iVentorDao { }
getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“aaaaa”)这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”)@Scope(“prototype”)来改变。
可以使用以下方式指定初始化方法和销毁方法(方法名任意):
@PostConstruct
public void init() { } @PreDestroy
public void destory() { }
复制代码
@RequiresPermission

例如: @RequiresPermissions({"file:read", "write:aFile.txt"} )

  void someMethod();
 
要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。
原文地址:https://www.cnblogs.com/myinspire/p/7273141.html