自从spring 4.0 开放以后,可以添加很多新特性的注解了。使用系统定义好的注解可以大大方便的提高开发的效率。

下面我贴一段代码来讲解注解:

通过小小的注解我们支持了以下功能:

  • 使 spring.jackson.date-format 属性支持 JDK8 日期格式化
  • 解决 request.getInputStream() 一次读取后失效痛点
  • 国际化支持
  • 全局跨域支持
  • 接口加密/解密
  • 防XSS攻击
  • 分布式限流/分布式锁支持

我们通过自定义@EnableCorsFilter 来看一下跨域是如何支持的:

  1. package com.battcn.boot.request.annotation;
  2.  
  3. import com.battcn.boot.request.configuration.cors.CorsFilterAutoConfiguration;
  4. import org.springframework.context.annotation.Import;
  5.  
  6. import java.lang.annotation.*;
  7.  
  8. /**
  9. * 开启跨域支持
  10. *
  11. * @author Levin
  12. * @since 2019-01-01
  13. */
  14. @Target({ElementType.TYPE})
  15. @Retention(RetentionPolicy.RUNTIME)
  16. @Documented
  17. @Inherited
  18. @Import({CorsFilterAutoConfiguration.class})
  19. public @interface EnableCorsFilter {
  20.  
  21. }

@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。 
如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。 

  1. CorsFilterAutoConfiguration类(具体实现)
  1. package com.battcn.boot.request.configuration.cors;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  5. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.web.cors.CorsConfiguration;
  9. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  10. import org.springframework.web.filter.CorsFilter;
  11.  
  12. import static com.battcn.boot.request.utils.StringUtils.defaultString;
  13.  
  14. /**
  15. * Cors 跨域支持
  16. *
  17. * @author Levin
  18. * @since 2017/12/5 0005
  19. */
  20. @Configuration
  21. @EnableConfigurationProperties(value = {CorsFilterProperties.class})
  22. public class CorsFilterAutoConfiguration {
  23.  
  24. private static final String PATH = "/**";
  25.  
  26. private final CorsFilterProperties properties;
  27.  
  28. @Autowired
  29. public CorsFilterAutoConfiguration(CorsFilterProperties properties) {
  30. this.properties = properties;
  31. }
  32.  
  33. private CorsConfiguration buildConfig() {
  34. CorsConfiguration corsConfiguration = new CorsConfiguration();
  35. corsConfiguration.addAllowedOrigin(defaultString(properties.getOrigin(), CorsConfiguration.ALL));
  36. corsConfiguration.addAllowedHeader(defaultString(properties.getAllowedHeader(), CorsConfiguration.ALL));
  37. corsConfiguration.addAllowedMethod(defaultString(properties.getMethod(), CorsConfiguration.ALL));
  38. // 是否发送 Cookie 信息
  39. corsConfiguration.setAllowCredentials(properties.getAllowCredentials());
  40. if (properties.getMaxAge() != null) {
  41. corsConfiguration.setMaxAge(properties.getMaxAge());
  42. }
  43. if (properties.getExposedHeader() != null) {
  44. corsConfiguration.addExposedHeader(properties.getExposedHeader());
  45. }
  46. return corsConfiguration;
  47. }
  48.  
  49. /**
  50. * 跨域过滤器
  51. *
  52. * @return Cors过滤器
  53. */
  54. @Bean
  55. @ConditionalOnMissingBean
  56. public CorsFilter corsFilter() {
  57. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  58. source.registerCorsConfiguration(defaultString(properties.getPath(), PATH), buildConfig());
  59. return new CorsFilter(source);
  60. }
  61.  
  62. }
  1. @ConditionalOnMissingBean 属性相同,自动生成加载
  2.  
  3. @Configuration Ioc加载到bean
  4.  
  5. @EnableConfigurationProperties 加载class配置项
  1. @ConfigurationProperties  加载具体的配置参数
  2. CorsFilterProperties配置类
  1. package com.battcn.boot.request.configuration.cors;
  2.  
  3. import lombok.Data;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.lang.Nullable;
  6.  
  7. /**
  8. * Core 跨域相关配置
  9. *
  10. * @author Levin
  11. * @since 2017/12/5 0005
  12. */
  13. @Data
  14. @ConfigurationProperties("request.cors")
  15. public class CorsFilterProperties {
  16.  
  17. private Boolean enabled;
  18. private String path;
  19. private String origin;
  20. private String allowedHeader;
  21. private String method;
  22. private String exposedHeader;
  23.  
  24. @Nullable
  25. private Boolean allowCredentials;
  26.  
  27. @Nullable
  28. private Long maxAge;
  29.  
  30. }

 

application.properties配置项

我在类属性里定义的maxAge,但是application里面显示的是max-age,会自动帮做转换,如果使用maxAge属性参数也是可以取到值的(是不是spring帮做了匹配查找)。

完成以上操作,只要在SpringApplication 启动加上@EnableCorsFilter  就可以实现跨域了。

maven调用以下是快速使用方法:

  1. <dependency>
  2. <groupId>com.battcn</groupId>
  3. <artifactId>request-spring-boot-starter</artifactId>
  4. <version>1.0.8-RELEASE</version>
  5. </dependency>

感谢唐亚峰提供的工具类。

Spring Boot Web 自定义注解篇(注解很简单很好用)的更多相关文章

  1. Spring Boot Web 自定义返回值(通用)

    在项目下新建common.entity包,包中包含两个文件Result数据类,ResultCode接口文件 Result.class @Data @NoArgsConstructor public c ...

  2. Spring Boot 2.0 教程 | @ModelAttribute 注解

    欢迎关注微信公众号: 小哈学Java 文章首发于个人网站: https://www.exception.site/springboot/spring-boot-model-attribute Spri ...

  3. Spring Boot 入门之基础篇(一)

    原文地址:Spring Boot 入门之基础篇(一) 博客地址:http://www.extlight.com 一.前言 Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是 ...

  4. spring boot(一):入门篇

    构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...

  5. spring boot实战(第十三篇)自动配置原理分析

    前言 spring Boot中引入了自动配置,让开发者利用起来更加的简便.快捷,本篇讲利用RabbitMQ的自动配置为例讲分析下Spring Boot中的自动配置原理. 在上一篇末尾讲述了Spring ...

  6. Springboot 系列(七)Spring Boot web 开发之异常错误处理机制剖析

    前言 相信大家在刚开始体验 Springboot 的时候一定会经常碰到这个页面,也就是访问一个不存在的页面的默认返回页面. 如果是其他客户端请求,如接口测试工具,会默认返回JSON数据. { &quo ...

  7. Spring Boot(一):入门篇+前端访问后端

    转自:Spring Boot(一):入门篇 什么是Spring Boot Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发 ...

  8. Spring Boot2 系列教程(十八)Spring Boot 中自定义 SpringMVC 配置

    用过 Spring Boot 的小伙伴都知道,我们只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好,但是,真实的项目环境比 ...

  9. Springboot 系列(六)Spring Boot web 开发之拦截器和三大组件

    1. 拦截器 Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分.并没有本质的不同,都是通过实现 HandlerInterceptor ...

随机推荐

  1. 计算机的Cache和Memory访问时Write-back,Write-through及write allocate的区别

    计算机的存储系统采用Register,Cache,Memory和I/O的方式来构成存储系统,无疑是一个性能和经济性的妥协的产物.Cache和Memory机制是计算机硬件的基础内容,这里就不再啰嗦.下面 ...

  2. 第六章 MySQL 查询

    查询数据表 语法: SELECT {* | <字段列表>} [ FROM <表1>, <表2>.... [ where <表达式> ] [ group ...

  3. 百度搜索(jsonp)

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>百 ...

  4. 集群搭建(一)克隆虚拟机静态IP设置

    [抛出问题] 当在搭建集群的时候,我们会将一个安装好相关程序的虚拟机进行克隆,克隆之后,我们会发下一些问题:就是原先的eth0 网卡不见了 原先的网卡 而克隆之后的网卡 会发现原来的网卡eth0 变为 ...

  5. QT5:C++实现基于multimedia的音乐播放器(二)

    今天接着上一篇来实现播放器的槽函数. 先来实现播放模式,槽函数如下: //播放模式 void Music::musicPlayPattern() { //z=++z%3; ) { //顺序播放 pla ...

  6. debain 安装nodejs

    apt-get update -yapt-get install -y build-essential curl curl -sL https://deb.nodesource.com/setup_8 ...

  7. PAT1081:Rational Sum

    1081. Rational Sum (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given N ...

  8. urllib使用

    1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=Fals ...

  9. CentOS7快速搭建LNMP环境

    名词解释: LNMP:Linux+Nginx+MySql+PHPLAMP:LInux+Apache+MySql+PHPNginx的正确读法应该是Engine X我们使用CentOS自带的YUM来安装 ...

  10. 网络IO和磁盘IO详解

    1. 缓存IO 缓存I/O又被称作标准I/O,大多数文件系统的默认I/O操作都是缓存I/O.在Linux的缓存I/O机制中,数据先从磁盘复制到内核空间的缓冲区,然后从内核空间缓冲区复制到应用程序的地址 ...