九、SpringBoot项目打包部署与全局异常捕获

一、全局异常捕获

  • 1.全局异常捕获注解
    • @ExceptionHandler 表示拦截异常
    • @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
    • @ControllerAdvice 可以指定扫描范围
    • @ControllerAdvice 约定了几种可行的返回值
      • 如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换
      • 返回 String,表示跳到某个 view
      • 返回 modelAndView
      • 返回 model + @ResponseBody
  • 2.Service代码
    • 异常访问:http://localhost:8088/sjyl/insertUser?age=0
@RestController
@Slf4j
public class MemberService {
    @RequestMapping("/insertUser")
    public int insertUser(int age) {
        int j = 1 / age;
        return j;
    }
}
  • 3.全局捕获异常实现
@ControllerAdvice
public class SjylExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<Object, Object> exceptionHandler() {
        HashMap<Object, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("msg", "系统错误");
        return result;
    }
}

浏览器访问:http://localhost:8088/sjyl/insertUser?age=0
在这里插入图片描述

二、SpringBoot项目打包

由于我们的SpringBoot项目已经内置了tomcat容器,所以我们不需要像SpringMVC那样打成war包,我们打成jar包就可以了
打包:使用mvn clean package打包
运行:使用java –jar 包名运行

  • 1.进入到项目主目录,删除target目录

在这里插入图片描述

  • 2.进入cmd命令

在这里插入图片描述

  • 3.打包命令mvn clean package

在这里插入图片描述

  • 4.运行命令java -jar (上一步生成的jar包路径地址)
    • D:\test\springboot_helloworld>java -jar D:\test\springboot_helloworld\target\springboot_helloworld-1.0-SNAPSHOT.jar

在这里插入图片描述

  • 5.运行报错(没有主清单)的解决方案
    • 在pom中加上如下配置即可
    • <mainClass>com.sjyl.App</mainClass>:需要配置成项目启动类的全限定类名

在这里插入图片描述

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>com.sjyl.App</mainClass>
                <excludes>
                    <exclude>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                    </exclude>
                    <exclude>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无休止符

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值