springboot基础教程之三--Spring boot json转换框架 、全局异常捕捉以及Spring boot JPA连接数据库

目录

一、Spring boot json转换框架

二、springboot全局异常捕捉

三、Spring boot JPA连接数据库


最新最全的计算机专业考研资料和程序员技术类文章免费送啦,进来看看吧。让你的学习、工作省时省力省钱

一、Spring boot json转换框架

个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析呢?

 <dependencies>

        <dependency>

           <groupId>com.alibaba</groupId>

           <artifactId>fastjson</artifactId>

           <version>1.2.15</version>

</dependencies>

       这里要说下很重要的话,官方文档说的1.2.10以后,会有两个方法支持HttpMessageconvert,一个是FastJsonHttpMessageConverter,支持4.2以下的版本,一个是FastJsonHttpMessageConverter4支持4.2以上的版本,具体有什么区别暂时没有深入研究。这里也就是说:低版本的就不支持了,所以这里最低要求就是1.2.10+。

配置fastjon

支持两种方法:

第一种方法:

(1)启动类继承extends WebMvcConfigurerAdapter

(2)覆盖方法configureMessageConverters

第二种方法:

(1)在App.java启动类中,注入Bean : HttpMessageConverters

具体代码如下:

代码:App.java

import java.util.List;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.http.converter.HttpMessageConverter;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

//如果想集成其他的json框架需要继承WebMvcConfigurerAdapter,并重写configureMessageConverters

@SpringBootApplication

public class App extends WebMvcConfigurerAdapter {

       // 第一种方式,重写configureMessageConverters,并将FastJsonConverter设置到系统中

       @Override

       public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

              FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

              converter.setFeatures(SerializerFeature.PrettyFormat);

              converters.add(converter);

              super.configureMessageConverters(converters);

       }

       // 第二种方法:注入beanHttpMessageConverters

       /*

        * @Bean public HttpMessageConverters faMessageConverters(){

* return new HttpMessageConverters(new FastJsonHttpMessageConverter()); }

        */

       public static void main(String[] args) {

              SpringApplication.run(App.class, args);

       }

}

二、springboot全局异常捕捉

在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢?

新建一个类GlobalDefaultExceptionHandler,

在class注解上@ControllerAdvice,

@ControllerAdvice:即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。非常简单,不过只有当使用@ExceptionHandler最有用,另外两个用处不大。

在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下


package com.hpit.base.exception;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

 

@ControllerAdvice

publicclass GlobalDefaultExceptionHandler {

   

    @ExceptionHandler(value = Exception.class)

    publicvoid defaultErrorHandler(HttpServletRequest req, Exception e)  {

//      // If the exception is annotated with @ResponseStatus rethrow it and let

//      // the framework handle it - like the OrderNotFoundException example

//      // at the start of this post.

//      // AnnotationUtils is a Spring Framework utility class.

//      if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)

//          throw e;

//

//      // Otherwise setup and send the user to a default error-view.

//      ModelAndView mav = new ModelAndView();

//      mav.addObject("exception", e);

//      mav.addObject("url", req.getRequestURL());

//      mav.setViewName(DEFAULT_ERROR_VIEW);

//      return mav;

      

      //打印异常信息:

       e.printStackTrace();

       System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()");

 

       /*

        * 返回json数据或者String数据:

        * 那么需要在方法上加上注解:@ResponseBody

        * 添加return即可。

        */

       

       /*

        * 返回视图:

        * 定义一个ModelAndView即可,

        * 然后return;

        * 定义视图文件(比如:error.html,error.ftl,error.jsp);

        *

        */

  }

   }

com.hpit.test.web.DemoController 加入方法:

@RequestMapping("/zeroException")

    publicint zeroException(){

       return 100/0;

    }

访问:http://127.0.0.1:8080/zeroException 这个方法肯定是抛出异常的,那么在控制台就可以看到我们全局捕捉的异常信息了

三、Spring boot JPA连接数据库

​​​​​​​在任何一个平台都逃离不了数据库的操作,那么在spring boot中怎么接入数据库呢?

很简单,我们需要在application.properties进行配置一下,application.properties路径是src/main/resources下,对于application.properties更多的介绍请自行百度进行查找相关资料进行查看,在此不进行过多的介绍,以下只是mysql的配置文件。

       大体步骤:

       (1)在application.properties中加入datasouce的配置

       (2)在pom.xml加入mysql的依赖。

    (3)获取DataSouce的Connection进行测试。

src/main/resouces/application.properties:

spring.datasource.url = jdbc:mysql://localhost:3306/test

spring.datasource.username = root

spring.datasource.password = root

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.min-idle=8

spring.datasource.initial-size=10

pom.xml配置:

<dependency>

       <groupId>mysql</groupId>

       <artifactId>mysql-connector-java</artifactId>

</dependency>

到此相关配置就ok了,那么就可以在项目中进行测试了,我们可以新建一个class Demo进行测试,实体类创建完毕之后,我们可能需要手动进行编写建表语句,这时候我们可能就会想起Hibernate的好处了。那么怎么在spring boot使用Hibernate好的特性呢?So easy,具体怎么操作,请看下篇之JPA – Hibernate

猜你喜欢

转载自blog.csdn.net/xiejiachao/article/details/121214663