资讯专栏INFORMATION COLUMN

Spring Boot 进阶

galaxy_robot / 1896人阅读

摘要:我们可不可以提供一个公共的入口进行统一的异常处理呢当然可以。一般我们可以在地址上带上版本号,也可以在参数上带上版本号,还可以再里带上版本号,这里我们在地址上带上版本号,大致的地址如,其中,即代表的是版本号。

上一篇带领大家初步了解了如何使用 Spring Boot 搭建框架,通过 Spring Boot 和传统的 SpringMVC 架构的对比,我们清晰地发现 Spring Boot 的好处,它使我们的代码更加简单,结构更加清晰。

从这一篇开始,我将带领大家更加深入的认识 Spring Boot,将 Spring Boot 涉及到东西进行拆解,从而了解 Spring Boot 的方方面面。学完本文后,读者可以基于 Spring Boot 搭建更加复杂的系统框架。

我们知道,Spring Boot 是一个大容器,它将很多第三方框架都进行了集成,我们在实际项目中用到哪个模块,再引入哪个模块。比如我们项目中的持久化框架用 MyBatis,则在 pom.xml 添加如下依赖:

</>复制代码

  1. org.mybatis.spring.boot
  2. mybatis-spring-boot-starter
  3. 1.1.1
  4. mysql
  5. mysql-connector-java
  6. 5.1.40

yaml/properties 文件

我们知道整个 Spring Boot 项目只有一个配置文件,那就是 application.yml,Spring Boot 在启动时,就会从 application.yml 中读取配置信息,并加载到内存中。上一篇我们只是粗略的列举了几个配置项,其实 Spring Boot 的配置项是很多的,本文我们将学习在实际项目中常用的配置项(注:为了方便说明,配置项均以 properties 文件的格式写出,后续的实际配置都会写成 yaml 格式)。

下面是我参与的某个项目的 application.yml 配置文件内容:

</>复制代码

  1. server:
  2. port: 8080
  3. context-path: /api
  4. tomcat:
  5. max-threads: 1000
  6. min-spare-threads: 50
  7. connection-timeout: 5000
  8. spring:
  9. profiles:
  10. active: dev
  11. http:
  12. multipart:
  13. maxFileSize: -1
  14. datasource:
  15. url: jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=true
  16. username: root
  17. password: root
  18. driverClassName: com.mysql.jdbc.Driver
  19. jpa:
  20. database: MYSQL
  21. showSql: true
  22. hibernate:
  23. namingStrategy: org.hibernate.cfg.ImprovedNamingStrategy
  24. properties:
  25. hibernate:
  26. dialect: org.hibernate.dialect.MySQL5Dialect
  27. mybatis:
  28. configuration:
  29. #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
  30. map-underscore-to-camel-case: true

以上列举了常用的配置项,所有配置项信息都可以在官网中找到,本课程就不一一列举了。

多环境配置

在一个企业级系统中,我们可能会遇到这样一个问题:开发时使用开发环境,测试时使用测试环境,上线时使用生产环境。每个环境的配置都可能不一样,比如开发环境的数据库是本地地址,而测试环境的数据库是测试地址。那我们在打包的时候如何生成不同环境的包呢?

这里的解决方案有很多:

1.每次编译之前手动把所有配置信息修改成当前运行的环境信息。这种方式导致每次都需要修改,相当麻烦,也容易出错。
2.利用 Maven,在 pom.xml 里配置多个环境,每次编译之前将 settings.xml 里面修改成当前要编译的环境 ID。这种方式会事先设置好所有环境,缺点就是每次也需要手动指定环境,如果环境指定错误,发布时是不知道的。
3.第三种方案就是本文重点介绍的,也是作者强烈推荐的方式。

首先,创建 application.yml 文件,在里面添加如下内容:

</>复制代码

  1. spring:
  2. profiles:
  3. active: dev

含义是指定当前项目的默认环境为 dev,即项目启动时如果不指定任何环境,Spring Boot 会自动从 dev 环境文件中读取配置信息。我们可以将不同环境都共同的配置信息写到这个文件中。

然后创建多环境配置文件,文件名的格式为:application-{profile}.yml,其中,{profile} 替换为环境名字,如 application-dev.yml,我们可以在其中添加当前环境的配置信息,如添加数据源:

</>复制代码

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=true
  4. username: root
  5. password: root
  6. driverClassName: com.mysql.jdbc.Driver

这样,我们就实现了多环境的配置,每次编译打包我们无需修改任何东西,编译为 jar 文件后,运行命令:

</>复制代码

  1. java -jar api.jar --spring.profiles.active=dev

其中 --spring.profiles.active 就是我们要指定的环境。

常用注解

我们知道,Spring Boot 主要采用注解的方式,在上一篇的入门实例中,我们也用到了一些注解。

本文,我将详细介绍在实际项目中常用的注解。

@SpringBootApplication

我们可以注意到 Spring Boot 支持 main 方法启动,在我们需要启动的主类中加入此注解,告诉 Spring Boot,这个类是程序的入口。如:

</>复制代码

  1. @SpringBootApplication
  2. public class Application {
  3. public static void main(String[] args) {
  4. SpringApplication.run(Application.class, args);
  5. }
  6. }

如果不加这个注解,程序是无法启动的。

我们查看下 SpringBootApplication 的源码,源码如下:

</>复制代码

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(excludeFilters = {
  8. @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  9. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  10. public @interface SpringBootApplication {
  11. /**
  12. * Exclude specific auto-configuration classes such that they will never be applied.
  13. * @return the classes to exclude
  14. */
  15. @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
  16. Class[] exclude() default {};
  17. /**
  18. * Exclude specific auto-configuration class names such that they will never be
  19. * applied.
  20. * @return the class names to exclude
  21. * @since 1.3.0
  22. */
  23. @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
  24. String[] excludeName() default {};
  25. /**
  26. * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
  27. * for a type-safe alternative to String-based package names.
  28. * @return base packages to scan
  29. * @since 1.3.0
  30. */
  31. @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
  32. String[] scanBasePackages() default {};
  33. /**
  34. * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
  35. * scan for annotated components. The package of each class specified will be scanned.
  36. *

  37. * Consider creating a special no-op marker class or interface in each package that
  38. * serves no purpose other than being referenced by this attribute.
  39. * @return base packages to scan
  40. * @since 1.3.0
  41. */
  42. @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
  43. Class[] scanBasePackageClasses() default {};
  44. }

在这个注解类上有3个注解,如下:

</>复制代码

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan(excludeFilters = {
  4. @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  5. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

因此,我们可以用这三个注解代替 SpringBootApplication,如:

</>复制代码

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan
  4. public class Application {
  5. public static void main(String[] args) {
  6. SpringApplication.run(Application.class, args);
  7. }
  8. }

其中,SpringBootConfiguration 表示 Spring Boot 的配置注解,EnableAutoConfiguration 表示自动配置,ComponentScan 表示 Spring Boot 扫描 Bean 的规则,比如扫描哪些包。

@Configuration
加入了这个注解的类被认为是 Spring Boot 的配置类,我们知道可以在 application.yml 设置一些配置,也可以通过代码设置配置。

如果我们要通过代码设置配置,就必须在这个类上标注 Configuration 注解。如下代码:

</>复制代码

  1. @Configuration
  2. public class WebConfig extends WebMvcConfigurationSupport{
  3. @Override
  4. protected void addInterceptors(InterceptorRegistry registry) {
  5. super.addInterceptors(registry);
  6. registry.addInterceptor(new ApiInterceptor());
  7. }
  8. }

不过 Spring Boot 官方推荐 Spring Boot 项目用 SpringBootConfiguration 来代替 Configuration。

@Bean

这个注解是方法级别上的注解,主要添加在 @Configuration 或 @SpringBootConfiguration 注解的类,有时也可以添加在 @Component 注解的类。它的作用是定义一个Bean。

请看下面代码:

</>复制代码

  1. @Bean
  2. public ApiInterceptor interceptor(){
  3. return new ApiInterceptor();
  4. }

那么,我们可以在 ApiInterceptor 里面注入其他 Bean,也可以在其他 Bean 注入这个类。

@Value

通常情况下,我们需要定义一些全局变量,都会想到的方法是定义一个 public static 变量,在需要时调用,是否有其他更好的方案呢?答案是肯定的。下面请看代码:

</>复制代码

  1. @Value("${server.port}")
  2. String port;
  3. @RequestMapping("/hello")
  4. public String home(String name) {
  5. return "hi "+name+",i am from port:" +port;
  6. }

其中,server.port 就是我们在 application.yml 里面定义的属性,我们可以自定义任意属性名,通过 @Value 注解就可以将其取出来。

它的好处不言而喻:

1.定义在配置文件里,变量发生变化,无需修改代码。
2.变量交给Spring来管理,性能更好。

注: 本课程默认针对于对 SpringMVC 有所了解的读者,Spring Boot 本身基于 Spring 开发的,因此,本文不再讲解其他 Spring 的注解。

注入任何类

本节通过一个实际的例子来讲解如何注入一个普通类,并且说明这样做的好处。

假设一个需求是这样的:项目要求使用阿里云的 OSS 进行文件上传。

我们知道,一个项目一般会分为开发环境、测试环境和生产环境。OSS 文件上传一般有如下几个参数:appKey、appSecret、bucket、endpoint 等。不同环境的参数都可能不一样,这样便于区分。按照传统的做法,我们在代码里设置这些参数,这样做的话,每次发布不同的环境包都需要手动修改代码。

这个时候,我们就可以考虑将这些参数定义到配置文件里面,通过前面提到的 @Value 注解取出来,再通过 @Bean 将其定义为一个 Bean,这时我们只需要在需要使用的地方注入该 Bean 即可。

首先在 application.yml 加入如下内容:

</>复制代码

  1. appKey: 1
  2. appSecret: 1
  3. bucket: lynn
  4. endPoint: https://www.aliyun.com

其次创建一个普通类:

</>复制代码

  1. public class Aliyun {
  2. private String appKey;
  3. private String appSecret;
  4. private String bucket;
  5. private String endPoint;
  6. public static class Builder{
  7. private String appKey;
  8. private String appSecret;
  9. private String bucket;
  10. private String endPoint;
  11. public Builder setAppKey(String appKey){
  12. this.appKey = appKey;
  13. return this;
  14. }
  15. public Builder setAppSecret(String appSecret){
  16. this.appSecret = appSecret;
  17. return this;
  18. }
  19. public Builder setBucket(String bucket){
  20. this.bucket = bucket;
  21. return this;
  22. }
  23. public Builder setEndPoint(String endPoint){
  24. this.endPoint = endPoint;
  25. return this;
  26. }
  27. public Aliyun build(){
  28. return new Aliyun(this);
  29. }
  30. }
  31. public static Builder options(){
  32. return new Aliyun.Builder();
  33. }
  34. private Aliyun(Builder builder){
  35. this.appKey = builder.appKey;
  36. this.appSecret = builder.appSecret;
  37. this.bucket = builder.bucket;
  38. this.endPoint = builder.endPoint;
  39. }
  40. public String getAppKey() {
  41. return appKey;
  42. }
  43. public String getAppSecret() {
  44. return appSecret;
  45. }
  46. public String getBucket() {
  47. return bucket;
  48. }
  49. public String getEndPoint() {
  50. return endPoint;
  51. }
  52. }

然后在 @SpringBootConfiguration 注解的类添加如下代码:

</>复制代码

  1. @Value("${appKey}")
  2. private String appKey;
  3. @Value("${appSecret}")
  4. private String appSecret;
  5. @Value("${bucket}")
  6. private String bucket;
  7. @Value("${endPoint}")
  8. private String endPoint;
  9. @Bean
  10. public Aliyun aliyun(){
  11. return Aliyun.options()
  12. .setAppKey(appKey)
  13. .setAppSecret(appSecret)
  14. .setBucket(bucket)
  15. .setEndPoint(endPoint)
  16. .build();
  17. }

最后在需要的地方注入这个 Bean 即可:

</>复制代码

  1. @Autowired
  2. private Aliyun aliyun;

拦截器

我们在提供 API 的时候,经常需要对 API 进行统一的拦截,比如进行接口的安全性校验。

本节,我会讲解 Spring Boot 是如何进行拦截器设置的,请看接下来的代码。

创建一个拦截器类:ApiInterceptor,并实现 HandlerInterceptor 接口:

</>复制代码

  1. public class ApiInterceptor implements HandlerInterceptor {
  2. //请求之前
  3. @Override
  4. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  5. System.out.println("进入拦截器");
  6. return true;
  7. }
  8. //请求时
  9. @Override
  10. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  11. }
  12. //请求完成
  13. @Override
  14. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  15. }
  16. }

@SpringBootConfiguration 注解的类继承 WebMvcConfigurationSupport 类,并重写 addInterceptors 方法,将 ApiInterceptor 拦截器类添加进去,代码如下:

</>复制代码

  1. @SpringBootConfiguration
  2. public class WebConfig extends WebMvcConfigurationSupport{
  3. @Override
  4. protected void addInterceptors(InterceptorRegistry registry) {
  5. super.addInterceptors(registry);
  6. registry.addInterceptor(new ApiInterceptor());
  7. }
  8. }

异常处理

我们在 Controller 里提供接口,通常需要捕捉异常,并进行友好提示,否则一旦出错,界面上就会显示报错信息,给用户一种不好的体验。最简单的做法就是每个方法都使用 try catch 进行捕捉,报错后,则在 catch 里面设置友好的报错提示。如果方法很多,每个都需要 try catch,代码会显得臃肿,写起来也比较麻烦。

我们可不可以提供一个公共的入口进行统一的异常处理呢?当然可以。方法很多,这里我们通过 Spring 的 AOP 特性就可以很方便的实现异常的统一处理。

</>复制代码

  1. @Aspect
  2. @Component
  3. public class WebExceptionAspect {
  4. private static final Logger logger = LoggerFactory.getLogger(WebExceptionAspect.class);
  5. //凡是注解了RequestMapping的方法都被拦截 @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  6. private void webPointcut() {
  7. }
  8. /**
  9. * 拦截web层异常,记录异常日志,并返回友好信息到前端 目前只拦截Exception,是否要拦截Error需再做考虑
  10. *
  11. * @param e
  12. * 异常对象
  13. */
  14. @AfterThrowing(pointcut = "webPointcut()", throwing = "e")
  15. public void handleThrowing(Exception e) {
  16. e.printStackTrace();
  17. logger.error("发现异常!" + e.getMessage());
  18. logger.error(JSON.toJSONString(e.getStackTrace()));
  19. //这里输入友好性信息
  20. writeContent("出现异常");
  21. }
  22. /**
  23. * 将内容输出到浏览器
  24. *
  25. * @param content
  26. * 输出内容
  27. */
  28. private void writeContent(String content) {
  29. HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
  30. .getResponse();
  31. response.reset();
  32. response.setCharacterEncoding("UTF-8");
  33. response.setHeader("Content-Type", "text/plain;charset=UTF-8");
  34. response.setHeader("icop-content-type", "exception");
  35. PrintWriter writer = null;
  36. try {
  37. writer = response.getWriter();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. writer.print(content);
  42. writer.flush();
  43. writer.close();
  44. }
  45. }

这样,我们无需每个方法都添加 try catch,一旦报错,则会执行 handleThrowing 方法。

优雅的输入合法性校验

为了接口的健壮性,我们通常除了客户端进行输入合法性校验外,在 Controller 的方法里,我们也需要对参数进行合法性校验,传统的做法是每个方法的参数都做一遍判断,这种方式和上一节讲的异常处理一个道理,不太优雅,也不易维护。

其实,SpringMVC 提供了验证接口,下面请看代码:

</>复制代码

  1. @GetMapping("authorize")//GetMappingRequestMappingmethod=method.GET)的组合
  2. public void authorize(@Valid AuthorizeIn authorize, BindingResult ret){
  3. if(result.hasFieldErrors()){
  4. List errorList = result.getFieldErrors();
  5. //通过断言抛出参数不合法的异常
  6. errorList.stream().forEach(item -> Assert.isTrue(false,item.getDefaultMessage()));
  7. }
  8. }
  9. public class AuthorizeIn extends BaseModel{
  10. @NotBlank(message = "缺少response_type参数")
  11. private String responseType;
  12. @NotBlank(message = "缺少client_id参数")
  13. private String ClientId;
  14. private String state;
  15. @NotBlank(message = "缺少redirect_uri参数")
  16. private String redirectUri;
  17. public String getResponseType() {
  18. return responseType;
  19. }
  20. public void setResponseType(String responseType) {
  21. this.responseType = responseType;
  22. }
  23. public String getClientId() {
  24. return ClientId;
  25. }
  26. public void setClientId(String clientId) {
  27. ClientId = clientId;
  28. }
  29. public String getState() {
  30. return state;
  31. }
  32. public void setState(String state) {
  33. this.state = state;
  34. }
  35. public String getRedirectUri() {
  36. return redirectUri;
  37. }
  38. public void setRedirectUri(String redirectUri) {
  39. this.redirectUri = redirectUri;
  40. }
  41. }

在 controller 的方法需要校验的参数后面必须跟 BindingResult,否则无法进行校验。但是这样会抛出异常,对用户而言不太友好!

那怎么办呢?

很简单,我们可以利用上一节讲的异常处理,对报错进行拦截:

</>复制代码

  1. @Component
  2. @Aspect
  3. public class WebExceptionAspect implements ThrowsAdvice{
  4. public static final Logger logger = LoggerFactory.getLogger(WebExceptionAspect.class);
  5. //拦截被GetMapping注解的方法 @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
  6. private void webPointcut() {
  7. }
  8. @AfterThrowing(pointcut = "webPointcut()",throwing = "e")
  9. public void afterThrowing(Exception e) throws Throwable {
  10. logger.debug("exception 来了!");
  11. if(StringUtils.isNotBlank(e.getMessage())){
  12. writeContent(e.getMessage());
  13. }else{
  14. writeContent("参数错误!");
  15. }
  16. }
  17. /**
  18. * 将内容输出到浏览器
  19. *
  20. * @param content
  21. * 输出内容
  22. */
  23. private void writeContent(String content) {
  24. HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
  25. .getResponse();
  26. response.reset();
  27. response.setCharacterEncoding("UTF-8");
  28. response.setHeader("Content-Type", "text/plain;charset=UTF-8");
  29. response.setHeader("icop-content-type", "exception");
  30. PrintWriter writer = null;
  31. try {
  32. writer = response.getWriter();
  33. writer.print((content == null) ? "" : content);
  34. writer.flush();
  35. writer.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }

这样当我们传入不合法的参数时就会进入 WebExceptionAspect 类,从而输出友好参数。

我们再把验证的代码多带带封装成方法:

</>复制代码

  1. protected void validate(BindingResult result){
  2. if(result.hasFieldErrors()){
  3. List errorList = result.getFieldErrors();
  4. errorList.stream().forEach(item -> Assert.isTrue(false,item.getDefaultMessage()));
  5. }
  6. }

这样每次参数校验只需要调用 validate 方法就行了,我们可以看到代码的可读性也大大的提高了。

接口版本控制

一个系统上线后会不断迭代更新,需求也会不断变化,有可能接口的参数也会发生变化,如果在原有的参数上直接修改,可能会影响线上系统的正常运行,这时我们就需要设置不同的版本,这样即使参数发生变化,由于老版本没有变化,因此不会影响上线系统的运行。

一般我们可以在地址上带上版本号,也可以在参数上带上版本号,还可以再 header 里带上版本号,这里我们在地址上带上版本号,大致的地址如:http://api.example.com/v1/test,其中,v1 即代表的是版本号。具体做法请看代码:

</>复制代码

  1. @Target({ElementType.METHOD,ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Mapping
  5. public @interface ApiVersion {
  6. /**
  7. * 标识版本号
  8. * @return
  9. */
  10. int value();
  11. }
  12. public class ApiVersionCondition implements RequestCondition {
  13. // 路径中版本的前缀, 这里用 /v[1-9]/的形式
  14. private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(d+)/");
  15. private int apiVersion;
  16. public ApiVersionCondition(int apiVersion){
  17. this.apiVersion = apiVersion;
  18. }
  19. @Override
  20. public ApiVersionCondition combine(ApiVersionCondition other) {
  21. // 采用最后定义优先原则,则方法上的定义覆盖类上面的定义
  22. return new ApiVersionCondition(other.getApiVersion());
  23. }
  24. @Override
  25. public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
  26. Matcher m = VERSION_PREFIX_PATTERN.matcher(request.getRequestURI());
  27. if(m.find()){
  28. Integer version = Integer.valueOf(m.group(1));
  29. if(version >= this.apiVersion)
  30. {
  31. return this;
  32. }
  33. }
  34. return null;
  35. }
  36. @Override
  37. public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
  38. // 优先匹配最新的版本号
  39. return other.getApiVersion() - this.apiVersion;
  40. }
  41. public int getApiVersion() {
  42. return apiVersion;
  43. }
  44. }
  45. public class CustomRequestMappingHandlerMapping extends
  46. RequestMappingHandlerMapping {
  47. @Override
  48. protected RequestCondition getCustomTypeCondition(Class handlerType) {
  49. ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
  50. return createCondition(apiVersion);
  51. }
  52. @Override
  53. protected RequestCondition getCustomMethodCondition(Method method) {
  54. ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
  55. return createCondition(apiVersion);
  56. }
  57. private RequestCondition createCondition(ApiVersion apiVersion) {
  58. return apiVersion == null ? null : new ApiVersionCondition(apiVersion.value());
  59. }
  60. }
  61. @SpringBootConfiguration
  62. public class WebConfig extends WebMvcConfigurationSupport {
  63. @Bean
  64. public AuthInterceptor interceptor(){
  65. return new AuthInterceptor();
  66. }
  67. @Override
  68. public void addInterceptors(InterceptorRegistry registry) {
  69. registry.addInterceptor(new AuthInterceptor());
  70. }
  71. @Override
  72. @Bean
  73. public RequestMappingHandlerMapping requestMappingHandlerMapping() {
  74. RequestMappingHandlerMapping handlerMapping = new CustomRequestMappingHandlerMapping();
  75. handlerMapping.setOrder(0);
  76. handlerMapping.setInterceptors(getInterceptors());
  77. return handlerMapping;
  78. }
  79. }

Controller 类的接口定义如下:

</>复制代码

  1. @ApiVersion(1)
  2. @RequestMapping("{version}/dd")
  3. public class HelloController{}

这样我们就实现了版本控制,如果增加了一个版本,则创建一个新的 Controller,方法名一致,ApiVersion 设置为2,则地址中 v1 会找到 ApiVersion 为1的方法,v2 会找到 ApiVersion 为2的方法。

自定义 JSON 解析

Spring Boot 中 RestController 返回的字符串默认使用 Jackson 引擎,它也提供了工厂类,我们可以自定义 JSON 引擎,本节实例我们将 JSON 引擎替换为 fastJSON,首先需要引入 fastJSON:

</>复制代码

  1. com.alibaba
  2. fastjson
  3. ${fastjson.version}

其次,在 WebConfig 类重写 configureMessageConverters 方法:

</>复制代码

  1. @Override
  2. public void configureMessageConverters(List> converters) {
  3. super.configureMessageConverters(converters);
  4. /*
  5. 1.需要先定义一个convert转换消息的对象;
  6. 2.添加fastjson的配置信息,比如是否要格式化返回的json数据
  7. 3.在convert中添加配置信息
  8. 4.将convert添加到converters中
  9. */
  10. //1.定义一个convert转换消息对象
  11. FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
  12. //2.添加fastjson的配置信息,比如:是否要格式化返回json数据
  13. FastJsonConfig fastJsonConfig=new FastJsonConfig();
  14. fastJsonConfig.setSerializerFeatures(
  15. SerializerFeature.PrettyFormat
  16. );
  17. fastConverter.setFastJsonConfig(fastJsonConfig);
  18. converters.add(fastConverter);
  19. }

单元测试

Spring Boot 的单元测试很简单,直接看代码:

</>复制代码

  1. @SpringBootTest(classes = Application.class)
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. public class TestDB {
  4. @Test
  5. public void test(){
  6. }
  7. }

模板引擎

在传统的 SpringMVC 架构中,我们一般将 JSP、HTML 页面放到 webapps 目录下面,但是 Spring Boot 没有 webapps,更没有 web.xml,如果我们要写界面的话,该如何做呢?

Spring Boot 官方提供了几种模板引擎:FreeMarker、Velocity、Thymeleaf、Groovy、mustache、JSP。

这里以 FreeMarker 为例讲解 Spring Boot 的使用。

首先引入 FreeMarker 依赖:

</>复制代码

  1. org.springframework.boot
  2. spring-boot-starter-freemarker

在 resources 下面建立两个目录:static 和 templates,如图所示:

其中 static 目录用于存放静态资源,譬如:CSS、JS、HTML 等,templates 目录存放模板引擎文件,我们可以在 templates 下面创建一个文件:index.ftl(freemarker 默认后缀为 .ftl),并添加内容:

</>复制代码

  1. Hello World!

然后创建 PageController 并添加内容:

</>复制代码

  1. @Controller
  2. public class PageController {
  3. @RequestMapping("index.html")
  4. public String index(){
  5. return "index";
  6. }
  7. }

启动 Application.java,访问:http://localhost:8080/index.html,就可以看到如图所示:

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76778.html

相关文章

  • 2019 Java 全栈工程师进阶路线图,一定要收藏

    摘要:结合我自己的经验,我整理了一份全栈工程师进阶路线图,给大家参考。乾坤大挪移第一层第一层心法,主要都是基本语法,程序设计入门,悟性高者十天半月可成,差一点的到个月也说不准。 技术更新日新月异,对于初入职场的同学来说,经常会困惑该往那个方向发展,这一点松哥是深有体会的。 我刚开始学习 Java 那会,最大的问题就是不知道该学什么,以及学习的顺序,我相信这也是很多初学者经常面临的问题。​我...

    wangdai 评论0 收藏0
  • SpringBoot进阶教程 | 第二篇:日志组件logback实现日志分级打印

    摘要:而的日志文件在由指定。创建启动类控制台打印开源项目本地日志打印效果这里因为配置中将不同级别的日志设置了在不同文件中打印,这样很大程度上方便项目出问题查找问题。 你是否因为项目出现问题,查找日志文件定位错误花费N多时间,是否为此苦不堪言,没关系!现在通过这篇文章,将彻底解决你的烦恼,这篇文篇介绍,如何通过logback配置文件将日志进行分级打印,一个配置文件彻底搞定日志查找得烦恼。 准备...

    yy736044583 评论0 收藏0
  • SpringBoot进阶教程 | 第一篇:YML多文档块实现多环境配置

    摘要:你是否为一个功能多个和多个文件区分不同运行环境配置,经常为这些配置文件的管理而头疼,现在通过这篇文章,将彻底解决你的烦恼,这篇文篇介绍,怎么通过文件构建多文档块,区分不同环境配置,自由切换不同环境启动项目,一个配置文件搞定。 你是否为SpringBoot一个功能多个yml和多个properties文件区分不同运行环境配置,经常为这些配置文件的管理而头疼,现在通过这篇文章,将彻底解决你的...

    shmily 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<