spring常用注解
WEB注解
@Controller
类/接口上标注,注册一个web请求
源码:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Controller { //用以标注spring beanName 可从spring容器中通过name获取 String value() default ""; }
使用示例:
@Controller public class TestController { @RequestMapping("/t1") @ResponseBody public String test(){ return "just test"; } }
@RestController
相当于@Controller和@ResponseBody的整合,返回数据体
源码:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { String value() default ""; }
示例:
@RestController public class TestController { @RequestMapping("/t1") public String test(){ return "just test"; } }
@RequestMapping
web请求控制,路径、参数、数据包类型等等
快捷注解:@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Mapping public @interface RequestMapping { //beanName 若类与方法都有值 则用#连接 String name() default ""; //请求路径 若类与方法都有值 则用/连接 @AliasFor("path") String[] value() default {}; //请求路径 若类与方法都有值 则用/连接 @AliasFor("value") String[] path() default {}; //请求方法类型:GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE //若类与方法都有值 取合集 RequestMethod[] method() default {}; //请求参数:eg {"a","b"} //若类与方法都有值 取合集 String[] params() default {}; //同上 String[] headers() default {}; //请求数据类型: //如:consumes = {"text/plain", "application/*"} String[] consumes() default {}; //返回数据类型 //如:consumes = {"text/plain", "application/*"} String[] produces() default {}; }
示例:
@RestController //类上通常只标注路径@RequestMapping("test") @RequestMapping(path = "test", method = RequestMethod.POST, params = {"a","b"}) public class TestController { /** * 类上支持POST请求 方法上支持GET请求 合集:支持POST和GET * 类上path=test 方法上path=t1 合并:test/t1 * 类上必有参数{"a","b"} 方法上必有参数{"c"} 合集:{"a","b","c"} * @return */ @RequestMapping(path = "t1", method = RequestMethod.GET, params = {"c"}) public String test(){ return "just test"; } }
@ResponseBody
以JSON形式返回给客户端(浏览器或其他的客户端) 前后端分离项目通常用@RestController注解, 此注解被隐含其中
@Controller public class TestController { @RequestMapping("/t1") @ResponseBody public String test(){ return "just test"; } }
@RequestBody @RequestParam
示例:
@RestController @RequestMapping("test") public class TestController { @RequestMapping("t1") public String test(@RequestBody JsonO jsonO, @RequestParam String password){ System.out.println(jsonO.toString()); System.out.println(password); return "just test"; } @Setter @Getter private static class JsonO implements Serializable { private Long id; private String name; @Override public String toString(){ return "id:"+id+",name:"+name; } } }
@ControllerAdvice @ExceptionHandler
主要有三种用途:1、全局异常处理 2、全局数据绑定 3、全局预处理
第2,3种能力实用性不是很强,并且通常可以通过线程缓存和别名处理,侧重说明全局异常处理
全局异常捕捉通常需要搭配全局统一返回,将返回数据封装在WebResponse或者ServiceResponse
@ControllerAdvice public class ControllerGlobaleExceptionHandler { /** * 捕捉一般异常 * @param e * @return */ @ExceptionHandler(Exception.class) public ServiceResponse exception(Exception e) { System.out.println("此处异常抛出:"+e); return new ServiceResponse(null); } /** * 捕捉自定义异常 * @param e * @return */ @ExceptionHandler(TestException.class) public ServiceResponse bizException(TestException e) { System.out.println("此处异常抛出:"+e); return new ServiceResponse(null); } }
@WebFilter
WEB过滤器,用的比较普遍的场景 1数据安全性校验 2访问限流 3特定数据抓取 4特定数据设定
这里以第4种为例,根据前端传入token获取访问者信息,然后存入线程缓存中(当然这里也可以验证token是否过期)
过滤器
@Component @WebFilter(filterName = "userFilter", urlPatterns = { "/*" }) public class UserFilter implements Filter { public static final ThreadLocal<String> userDetailThreadLocal = new ThreadLocal<String>(); @Override public void init(FilterConfig filterConfig) throws ServletException { //启动时执行 System.out.println("过滤器初始化"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //模拟查找用户信息 将用户信息放入当前线程 HttpServletRequest httpServletRequest = (HttpServletRequest)request; //从头部信息取出token String token = httpServletRequest.getHeader("access-token"); //token查询用户信息 String userName = getUserDetailByToken(token); //将用户信息存入线程缓存中 userDetailThreadLocal.set(userName); System.out.println("执行过滤"); //不要忘了执行过滤 chain.doFilter(request, response); } private String getUserDetailByToken(String token){ return "张先生"; } @Override public void destroy() { System.out.println("过滤器销毁"); } }
Controller
@RestController @RequestMapping("test") public class TestController { @RequestMapping("t1") public String test() { //这里获取刚刚过滤器存入线程缓存中的用户信息 return UserFilter.userDetailThreadLocal.get(); } }
@ConfigurationProerties
使用示例:
启动类开启动态配置:加注解@EnableConfigurationProperties
配置类和配置文件:
@ConfigurationProperties(prefix = "datasource") @Data public class DataSorceProperties { private String url; private String name; private String driverClass; } 配置文件 datasource.url=http;//dsidojd datasource.name=user datasource.driverClass=mysql
其他基本注解表: