【Springboot开发】后端代码基础框架

前言:主要介绍最基础的springboot开发架构

1. overall

在这里插入图片描述
核心部分主要是src包,main包存放的是后端代码,test是用于测试main包的代码。main包主要包含以下几个部分:

  • java:存放后端代码
  • resources:存放配置文件
  • webapp:存放资源文件,如前端jsp、图片资源等

2. 配置文件

springboot使用固定名字的配置文件:application.propertiesapplication.yml

2.1 YAML

基本语法

  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • 大小写敏感

yml举例

server:
  port: 8080

2.2 properties

properties举例:

spring.application.name=apply

2.3 配置文件加载顺序

  1. 按目录。位置高的将覆盖位置低的。
    在这里插入图片描述
  2. application.properties 的优先级高于 application.yml
  3. 互补读取:
  • 如果优先级高的配置文件中没有某个配置项,则会到优先级低的配置文件中找该配置项,即具有互补功能。
  • 文件名相同才会互补

2.4 多配置文件

有时候为了分开produce和test配置,会使用多个配置文件。
在这里插入图片描述
这种情况下可以在application.yml文件中指定使用的配置文件:
在这里插入图片描述

3. 代码包

代码包的路径为:
在这里插入图片描述
其中buildbaseframe为项目名。
后端代码主要包含以下几个部分:

  • BuildBaseFrameApplication: 启动类
  • utils:工具代码包
  • infrastructure
  • application
  • api

3.1 infrastructure

对应数据访问层,主要包含:

  • common包: 底层的一些公共配置
  • 模块包: 如用户模块
    在这里插入图片描述
    本节主要对各个模块包进行说明。

3.1.1 persistence

数据持久化层,主要包括mysqlrepository

  1. mysql
    主要是用来和数据库做绑定,映射对象到PO。
    在这里插入图片描述
    xml文件固定格式为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.buildbaseframe.infrastructure.user.persistence.mysql.mapper.UserPoMapper">
    <select id="findThis" resultType="com.example.buildbaseframe.infrastructure.user.persistence.repository.po.UserPo">
        select *
        from t_user
        where id = #{id}
    </select>
</mapper>

namespace是为了绑定mysql包下对应的映射文件,下写各种sql操作语句。
xxxPoMapper文件是为了做数据库对象和PO对象的映射,举例:

@Mapper
public interface UserPoMapper extends BaseMapper<UserPo> {

    /**
     * 测试xml方式绑定查询
     */

    UserPo findThis(@Param("id") Long id);

}
  • PoMapper文件只需要写一个接口继承自BaseMapper,类型名为同名的Po类(自定义)
  • PoMapper文件的方法名和xml文件中的操作id需要一致
  • @Param传入参数也需要和xml对应
  1. repository
    主要操作PO对象。
    在这里插入图片描述
    PO包
    将数据库表结构映射到JAVA,举例:
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@TableName("t_user")
public class UserPo extends BaseDatabasePo {
    private static final long serialVersionUID = 1L;

    /**
     * 用户昵称
     */
    @TableField(value = "name")
    private String nickname;

    /**
     * 用户头像url
     */
    @TableField(value = "avatar_url")
    private String avatarUrl;

    /**
     * 用户个人介绍
     */
    @TableField(value = "description")
    private String introduction;

    /**
     * 用户性别
     */
    @TableField(value = "gender")
    private Integer gender;

}

由于对PO对象有一些公共操作,通常先在common包中写一个公共类:

@Data
@EqualsAndHashCode(exclude = {"createTime", "updateTime"})
public class BaseDatabasePo implements Serializable {

    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    protected Long id;

    /**
     * 创建时间
     */
    @TableField
    protected LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField
    protected LocalDateTime updateTime;

}

repository接口
主要包含一些对数据对象的最基本的操作方法。举例:

public interface UserRepository {
    public UserPo get(Long userId);

    public int update(UserPo po, Long userId);

    public Long insertOneUser(UserPo userPo);
}

repository实现类
主要是对接口类的实现。

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserPoMapper mapper;

    @Override
    public UserPo get(Long userId) {
        return mapper.selectById(userId);
    }

    @Override
    public int update(UserPo po, Long userId) {
        UpdateWrapper<UserPo> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", userId);
        if (po.getNickname() != null)
            wrapper.set("nickname", po.getNickname());
        if (po.getAvatarUrl() != null)
            wrapper.set("avatar_url", po.getAvatarUrl());
        if (po.getIntroduction() != null)
            wrapper.set("introduction", po.getIntroduction());
        if (po.getGender() != null)
            wrapper.set("gender", po.getGender());
        return mapper.update(po, wrapper);
    }

    @Override
    public Long insertOneUser(UserPo userPo){
        mapper.insert(userPo);
        return userPo.getId();
    }
}
  • 先注入PoMapper对象,用于调用各种对数据库底层的操作

3.2 application

对应应用层,主要结构如下:
在这里插入图片描述

  • common包:公共配置,主要涉及到一些exception的处理
  • 各模块包
    主要讲解各模块包,结构如下,其中dto、converter、service是必须的:
    在这里插入图片描述

3.2.1 dto

前端给后端传递的数据,举例:

@Data
public class UserInfoDto {

    /**
     * 用户id
     */
    private Long id;

    /**
     * 用户昵称
     */
    private String nickname;

    /**
     * 用户头像url
     */
    private String avatarUrl;

    /**
     * 用户个人介绍
     */
    private String introduction;

    /**
     * 用户性别
     */
    private GenderEnum gender;

}

3.2.2 converter

只用写接口,具体方法会自动实现。用来实现Po和Dto对象之间的转换。

@Mapper(componentModel = "spring")
public interface UserAppConverter {

    UserInfoDto toUserInfoDto(UserPo po);

    UserPo toUserPo(UserInfoDto dto);

}

3.2.3 service

服务层的接口和实现,用来实现和数据访问层的交互。
接口

public interface UserService {

    public UserInfoDto getUserInfo(Long userId);

    public UserInfoDto updateUserInfo(UserInfoDto dto, Long userId);

    public Long insertOneUser(UserInfoDto userInfoDto);
}

实现类

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserAppConverter userAppConverter;

    /**
     * 根据id获取用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoDto getUserInfo(Long userId) {
        UserPo po = userRepository.get(userId);
        if (po == null) {
            throw new NotFoundException("用户信息");
        }

        System.out.println(po);

        return userAppConverter.toUserInfoDto(po);
    }

    /**
     * 更新用户信息
     * @param dto
     * @param userId
     * @return
     * @throws NotFoundException
     */
    @Override
    public UserInfoDto updateUserInfo(UserInfoDto dto, Long userId){
        UserPo po = userAppConverter.toUserPo(dto);
        if (userRepository.get(userId) == null) {
            throw new NotFoundException("用户信息");
        }
        int succ = userRepository.update(po, userId);
        return userAppConverter.toUserInfoDto(userRepository.get(userId));
    }

    /**
     * 添加新用户
     * @param userInfoDto
     * @return
     */
    @Override
    public Long insertOneUser(UserInfoDto userInfoDto){
        UserPo userPo = userAppConverter.toUserPo(userInfoDto);
        UserPo userPo1 = userRepository.findByName(userPo.getNickname());

        if(userPo1!=null){
            throw new BusinessException(ExceptionType.DUPLICATE_ERROR);
        }

        Long id = userRepository.insertOneUser(userPo);

        return id;
    }

}

3.3 api

控制器层,目录结构如下:
在这里插入图片描述

  • common包:公共类,包括异常捕获、权限、page验证等功能
  • 各模块包
    主要讲解模块包,结构如下:
    在这里插入图片描述

3.3.1 vo

数据视图对象,后端传给前端的数据。

@Data
public class UserInfoVo {

    /**
     * 用户id
     */
    private String id;

    /**
     * 用户昵称
     */
    private String nickname;

    /**
     * 用户头像url
     */
    private String avatarUrl;

    /**
     * 用户个人介绍
     */
    private String introduction;

    /**
     * 用户性别
     */
    private String gender;

}

3.3.2 req

对vo对象做检查。

@Data
public class UserCreateReq {

    /**
     * 用户昵称
     */
    @Length(min = 2, max = 64, message = "昵称长度应在2-64之间")
    private String nickname;

    /**
     * 用户头像url
     */
    @URL(message = "头像应当是有效的图片url")
    @Length(max = 255, message = "头像URL长度不能超过255")
    private String avatarUrl;

    /**
     * 用户个人介绍
     */
    @Length(max = 255, message = "用户介绍长度不能超过255")
    private String introduction;

    /**
     * 用户性别
     */
    @EnumStringValidate(value = GenderEnum.class, message = "不是有效的性别类型")
    private String gender;

}

3.3.3 converter

dto和vo对象的转换。

@Mapper(componentModel = "spring")
public interface UserApiConverter{

    @Mapping(source = "introduction", target = "description")
    UserInfoVo toUserInfoVo(UserInfoDto dto);

    @Mapping(source = "description", target = "introduction")
    UserInfoDto toUserInfoDto(UserCreateReq req);


}

3.3.4 controller

api的实现。

@Validated
@RestController // 既需要返回html数据又需要返回非html数据,类上使用@controller,方法上@requestcontroller或@responsebody
@Slf4j
@RequestMapping("/api/v1/user")
public class UserController {
    @Autowired
    private UserService service;

    @Autowired
    private UserApiConverter userApiConverter;

    @Autowired
    private GenderEnumConverter genderEnumConverter;

    /**
     * 用户获得自己的基本信息
     *
     * @param
     * @return
     * @methodName getOwnInfo
     */
    // 可以不用返回CommonResullt,有包装器会拦截
    @RequestMapping(value = "/info/own", method = RequestMethod.GET)
    public UserInfoVo getOwnInfo() {
        return userApiConverter.toUserInfoVo(service.getUserInfo(SecurityContextHolder.getUserId()));
    }

    /**
     * 根据id获得用户信息
     *
     * @param
     * @return
     * @methodName getUserInfo
     */
    @RequestMapping(value = "/info/{userId}", method = RequestMethod.GET)
    public UserInfoVo getUserInfo(@PathVariable("userId") String userId) {


        return userApiConverter.toUserInfoVo(service.getUserInfo(Long.valueOf(userId)));
    }

}

结语

以上是关于springboot的一个基本框架的梳理,具体细节方面的实现需要根据实际需求修改。

  • 10
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
核心功能 文章/图片/视频发布、喜欢、统计阅读次数。 文章标签tag功能、支持按tag分类 文章支持ueditor/markdown编辑器切换(后台配置) 评论功能,支持回复,支持表情。 第三方(微博、QQ)登录。 lucene实现的站内搜索。 响应式布局 支持用户订阅 先看效果图 SpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能) http://localhost:8080/admin/group/list SpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能)SpringBoot开发非常美观的java博客系统(包含后台管理功能) 技术选型: JDK8 数据库MySQL 主框架 (Spring-bootSpring-data-jpa) 安全权限 Shiro 搜索工具 Lucene 缓存 Ehcache 视图模板 Freemarker 其它 Jsoup、fastjson jQuery、Seajs Bootstrap 前端框架 UEditor/Markdown编辑器 font-Awesome 字体/图标 准备工作(sql文件在项目里面) 安装 Jdk8 安装 Maven 准备 IDE (如果你不看源码,可以忽略下面的步骤,直接通过Maven编译war包:mvn clean package -DskipTests) IDE 需要配置的东西 编码方式设为UTF-8 配置Maven 设置Jdk8 关于这些配置,网上有一大把的资料,所以此处不再重复。 获取代码导入到IDE 下载代码 导入到IDE的时候请选择以Maven的方式导入 项目配置参考 系统配置手册 配置完毕 启动项目,在控制台看到Mblog加载完毕的信息后,表示启动成功 打开浏览器输入:http//localhost/mblog/ (此处仅是示例,具体具体端口因人而异),访问成功即部署完毕 后台管理的地址是 /admin, 如果你是管理员账号点导航栏的头像会看到"后台管理" 启动成功后,你应该去后台的系统配置里配置你的网站信息等。 常见问题总结 进入系统后, 菜单加载不出来, 那应该是你没有导 db_init.sql 点标签显示乱码, 请设置Tomcat的 URIEncoding 为 UTF-8 项目截图 SpringBoot开发非常美观的java博客系统(包含后台管理功能) 转自:https://gitee.com/mtons/mblog SpringBoot开发非常美观的java博客系统(包含后台管理功能) 注意: 一、java main方式运行mblog-web下的BootApplication.java时抛出异常的解决方案 Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean. SpringBoot开发非常美观的java博客系统(包含后台管理功能) 注释掉后下面图片的这段后,记得maven要重新reimport SpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能) 否则maven依赖不生效还是会抛出以上的异常 二、第三方登录点击后无响应,那是因为第三方开放平台回调的url失效导致,需要你去对应的第三方开放平台注册app后获取对应的oauth帐号 SpringBoot开发非常美观的java博客系统(包含后台管理功能) 三、idea以maven项目导入该项目后,发现没有maven的依赖包时,需要对每个maven module进行clear和install,并且注意maven的依赖顺序 SpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能) 四、访问地址是http://localhost:8080 登录时,帐号,密码只要自己找个密码,然后md5下在更新到db中即可登录成功。 比如:zuidaima 111111,md5后密码是 3931MUEQD1939MQMLM4AISPVNE,md5的javaSpringBoot开发非常美观的java博客系统(包含后台管理功能) SpringBoot开发非常美观的java博客系统(包含后台管理功能)
一个完整的外卖系统,包括手机端,后台管理,api 基于spring boot和vue的前后端分离的外卖系统 包含完整的手机端,后台管理功能 技术选型 核心框架Spring Boot 数据库层:Spring data jpa/Spring data mongodb 数据库连接池:Druid 缓存:Ehcache 前端:Vue.js 数据库:mysql5.5以上,Mongodb4.0(不要使用最新版4.2) 模块 flash-waimai-mobile 手机端站点 flash-waimai-manage后台管理系统 flash-waimai-api java接口服务 flash-waimai-core 底层核心模块 flash-waimai-generate 代码生成模块 快速开始 数据存储采用了mysql和mongodb,其中基础管理配置功能数据使用mysql,业务数据使用mongodb存储。 创建mysql数据库 CREATE DATABASE IF NOT EXISTS waimai DEFAULT CHARSET utf8 COLLATE utf8_general_ci; CREATE USER 'waimai'@'%' IDENTIFIED BY 'waimai123'; GRANT ALL privileges ON waimai.* TO 'waimai'@'%'; flush privileges; mysql数据库创建好了之后,启动flash-waimai-api服务,会自动初始化数据,无需开发人员自己手动初始化数据 安装mongodb并创建数据库:flash-waimai 使用mongorestore命令 导入mongodb数据,由于测试数据量较大,打包放在了百度云盘:链接:https://pan.baidu.com/s/1mfO7yckFL7lMb_O0BPsviw 提取码:apgd 下载后将文件解压到d:\elm,如下命令导入数据: mongorestore.exe -d flash-waimai d:\\elm 下载项目测试数据的图片(商家和食品图片):链接:https://pan.baidu.com/s/1rvZDspoapWa6rEq2D_5kzw 提取码:urzw ,将图片存放到t_sys_cfg表中system.file.upload.path配置的目录下 启动管理平台:进入flash-waimai-manage目录:运行 npm install --registry=https://registry.npm.taobao.org运行npm run dev启动成功后访问 http://localhost:9528 ,登录,用户名密码:admin/admin 启动手机端:进入flash-waimai-mobile目录:运行 npm install --registry=https://registry.npm.taobao.org运行npm run local启动成功后访问 http://localhost:8000
Spring Boot是一个由Pivotal团队提供的全新框架,旨在简化新Spring应用程序的初始化搭建和开发过程。它采用特定的配置方式,使开发人员无需编写样板化的配置。Spring Boot的优点包括: 1. 简化配置:Spring Boot提供了自动配置的功能,大大减少了配置文件的编写工作,使开发更加便捷。 2. 快速开发Spring Boot提供了一套可靠的开发环境和开发工具,可以快速构建后端应用程序。 3. 自动化依赖管理:Spring Boot的依赖管理功能可以自动管理项目的依赖关系,简化了项目的依赖管理过程。 4. 内嵌服务器:Spring Boot内置了Tomcat等常用服务器,使得部署和运行应用程序变得更加简单。 5. 易于测试:Spring Boot提供了方便的测试工具和注解,可以轻松地进行单元测试和集成测试。 总之,Spring Boot是一个强大而灵活的后端框架,它通过简化配置、提供便利的开发工具和自动化依赖管理等特性,使得开发人员能够更加轻松地构建高效、可靠的后端应用程序。 [2 [3<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [后端框架SpringBoot入门](https://blog.csdn.net/qq_40401866/article/details/102480841)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【开发后端框架——SpringBoot](https://blog.csdn.net/qq_40479037/article/details/129786063)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值