当前位置: 首页 > wzjs >正文

中国建设银行巴黎分行网站手机端网站优化

中国建设银行巴黎分行网站,手机端网站优化,公司管理,长沙有哪些大型工厂后端开发:Spring Boot 快速开发实战 引言 在现代后端开发中,Spring Boot 因其轻量级、快速开发的特性而备受开发者青睐。本文将带你从零开始,使用 Spring Boot MyBatis 实现一个完整的 RESTful API,并深入探讨如何优雅地处理异…

后端开发:Spring Boot 快速开发实战

引言

在现代后端开发中,Spring Boot 因其轻量级、快速开发的特性而备受开发者青睐。本文将带你从零开始,使用 Spring Boot + MyBatis 实现一个完整的 RESTful API,并深入探讨如何优雅地处理异常和日志记录。无论你是初学者还是有一定经验的开发者,这篇笔记都能为你提供实用的知识点。


一、环境准备

1. 安装依赖工具

确保你已经安装了以下工具:

  • JDK 8 或更高版本
  • Maven(构建工具)
  • IDE(如 IntelliJ IDEA 或 VS Code)

2. 创建 Spring Boot 项目

使用 Spring Initializr 快速生成项目骨架:

  1. 访问 Spring Initializr 网站。
  2. 配置项目信息:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 最新稳定版本
    • Dependencies: 添加 Spring Web, MyBatis Framework, MySQL Driver
  3. 下载并解压项目,导入到 IDE 中。

二、Spring Boot + MyBatis 实现 RESTful API 的完整流程

1. 数据库设计

假设我们要开发一个简单的用户管理系统,包含以下字段:

  • id (主键)
  • name (用户名)
  • email (邮箱)
SQL 脚本
CREATE DATABASE user_management;USE user_management;CREATE TABLE users (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) NOT NULL UNIQUE
);

2. 配置数据库连接

application.properties 文件中配置 MySQL 数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml

3. 创建实体类

创建一个 User 实体类,与数据库表对应:

package com.example.demo.entity;public class User {private Long id;private String name;private String email;// Getters and Setters
}

4. 创建 Mapper 接口

使用 MyBatis 的注解或 XML 配置方式定义数据访问层接口:

package com.example.demo.mapper;import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;import java.util.List;@Mapper
public interface UserMapper {@Select("SELECT * FROM users")List<User> findAll();@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(User user);@Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}")void update(User user);@Delete("DELETE FROM users WHERE id=#{id}")void delete(Long id);
}

5. 创建 Service 层

封装业务逻辑,调用 Mapper 接口:

package com.example.demo.service;import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public List<User> getAllUsers() {return userMapper.findAll();}public User getUserById(Long id) {return userMapper.findById(id);}public void createUser(User user) {userMapper.insert(user);}public void updateUser(User user) {userMapper.update(user);}public void deleteUser(Long id) {userMapper.delete(id);}
}

6. 创建 Controller 层

暴露 RESTful API 接口:

package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PostMappingpublic void createUser(@RequestBody User user) {userService.createUser(user);}@PutMapping("/{id}")public void updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUser(id);}
}

三、如何优雅地处理异常和日志记录?

1. 全局异常处理

使用 @ControllerAdvice 注解实现全局异常处理,避免重复代码:

package com.example.demo.exception;import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception ex) {return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);}
}

自定义异常类:

package com.example.demo.exception;public class ResourceNotFoundException extends RuntimeException {public ResourceNotFoundException(String message) {super(message);}
}

2. 日志记录

使用 SLF4JLogback 记录日志,便于调试和问题追踪:

package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {private static final Logger logger = LoggerFactory.getLogger(UserController.class);@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {logger.info("Fetching all users");return userService.getAllUsers();}@PostMappingpublic void createUser(@RequestBody User user) {logger.info("Creating user: {}", user);userService.createUser(user);}
}

四、总结

通过本文,我们完成了以下内容:

  1. 使用 Spring Boot 和 MyBatis 实现了一个完整的 RESTful API。
  2. 学习了如何优雅地处理异常和记录日志。

这些技能是后端开发的核心能力,能够帮助你在实际项目中快速构建高效、稳定的系统。希望这篇文章能为你提供实用的指导,并助力你在以后的只有我道路上有目标,向钱进!

参考链接

  • Spring Boot 官方文档
  • MyBatis 官方文档
  • RESTful API 设计指南

http://www.dtcms.com/wzjs/165714.html

相关文章:

  • 怎么把自己的网站放到百度上企业网站怎么建立
  • wordpress碎语插件优化大师官网入口
  • 淘宝上网站建设靠谱吗今日新闻国内大事件
  • ubuntu怎么做网站网络平台怎么创建需要多少钱
  • 长沙网站建设有哪些seo综合查询爱站
  • 一个公司网站后台怎么做如何建网站
  • 用jsp做新闻网站久久seo正规吗
  • 对于做房产做网站的感悟短视频推广引流方案
  • 网站建站目标站长工具网站
  • 网站域名解析设置谷歌搜索引擎在线
  • 新疆今日头条新闻青岛seo结算
  • 如何做网站的二级页面搜索引擎优化文献
  • 营销型网站建设sempk营销软文网站
  • 民族文化网站建设的作用seo营销网站
  • 设置网站维护页面网络推广平台收费不便宜
  • 商城网站用什么做百度网站介绍
  • 网站建设伍金手指下拉9seo顾问培训
  • 手机网站特效免费的黄冈网站代码
  • 如何在网站源码做授权搜索引擎优化的办法有哪些
  • 深圳网站建设 百业品牌策划案例
  • 科技网站 网站建设全国互联网营销大赛官网
  • 网站可以免费建设吗网络公司名字
  • 海南网站公司网络推广的含义
  • 青岛手机网站制作网站快速收录
  • 网站建设幽默小学生抄写新闻20字
  • 做网站首选智投未来1合肥seo报价
  • 网站建设功能列表怎么做seo
  • 网站关键词用什么做国内最好的危机公关公司
  • 怎样开通网站上海网络推广公司
  • P2P网站怎么建设怎样推广网站