Spring Boot 2 个人App后端实践(1)

news2024/9/22 23:37:15

App使用Flutter,数据库考虑到要存储的对象并不规整选择使用MongoDB,尝试为自己的App搭建一个简易的后端。

 

1.通过IDEA脚手架创建项目

New Project->Spring Initializr->Next,输入相关信息并选择Java版本1.8,->Next选择依赖项(注意此时Spring Boot版本选择2.X.X),最后确定项目位置Finish,参考此处。

等待Maven依赖项下载加载。完成后,再添加对mongodb的依赖项。

此时pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>indi.nicolasHuang</groupId>
    <artifactId>lazymanrecipedemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>lazymanrecipedemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在项目下添加不同类的文件夹。

暂且添加如此多:

2.IDEA连接数据库

右侧选择Database,新建连接,在Database一栏,输入对应的已在本地创建完成的mongodb数据库名,可点击Test Connection测试是否能连接上,点击OK确定。

3.测试页面访问

测试页面访问需要先添加依赖thymeleaf,才能访问静态页面,于pom.xml中添加如下以方便测试:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>

在resources的templates中新建index.html作为欢迎页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Hello
</body>
</html>

同目录可以新建error.html作为报错页面。

在配置中心application.properties设置项目端口和mongodb详细数据:

# 应用名称
spring.application.name=lazymanrecipedemo
# 应用服务 WEB 访问端口
server.port=8080

#mongodb设置
# 数据库名称
spring.data.mongodb.database=lazymanrecipe
# 地址
spring.data.mongodb.host=localhost
# 端口
spring.data.mongodb.port=27017

设置好后启动项目,访问http://localhost:8080/,即为index.html(默认欢迎页面)。

4.添加实体类

在entity目录中新增实体类Recipe,作为食谱数据类,参考:

package indi.nicolashuang.lazymanrecipedemo.entity;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.io.Serializable;

@Document(collection = "recipe")
public class Recipe implements Serializable {

    @Id
    private ObjectId id;

    private Integer recipeIndex;

    private String name;

    private String type;

    private String foods;

    private String steps;

    @Field("created_time")
    private Long createdTime;

    public Recipe(){

    }

    public Recipe(String name, String type, String foods, String steps){
        this.name = name;
        this.type = type;
        this.foods = foods;
        this.steps = steps;
    }

    public Recipe(String id, Integer recipeIndex, String name, String type, String foods, String steps, Long createdTime) {
        this.id = new ObjectId(id);
        this.recipeIndex = recipeIndex;
        this.name = name;
        this.type = type;
        this.foods = foods;
        this.steps = steps;
        this.createdTime = createdTime;
    }

    public String getId() {
        return id.toHexString();
    }

    public void setId(String id) {
        this.id = new ObjectId(id);
    }

    public Integer getRecipeIndex() {
        return recipeIndex;
    }

    public void setRecipeIndex(Integer recipeIndex) {
        this.recipeIndex = recipeIndex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getFoods() {
        return foods;
    }

    public void setFoods(String foods) {
        this.foods = foods;
    }

    public String getSteps() {
        return steps;
    }

    public void setSteps(String steps) {
        this.steps = steps;
    }

    public Long getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Long createdTime) {
        this.createdTime = createdTime;
    }
}

尝试做了下构造方法内部的转换。

5.数据库访问测试

在text->java->indi->nicolashuang->lazymanrecipedemo目录下进行mongodb数据库访问测试,新建MongodbTests.java:

package indi.nicolashuang.lazymanrecipedemo;

import indi.nicolashuang.lazymanrecipedemo.entity.Recipe;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;

import javax.annotation.Resource;

@SpringBootTest
class MongodbTests {

    @Resource
    private MongoTemplate mongoTemplate;

    @Test
    public void findId(){
        Recipe recipe = mongoTemplate.findById("6392d1c6ba580db0d7a105aa", Recipe.class);
        assert recipe != null;
        System.out.println(recipe.getName());
    }
}

报错:Test包出现Autowired注入提示Could not autowire. No beans of 'Autowired' type found.多次尝试后替换为@Resource,此时运行Test可以得到recipe的name。

6.控制层

编写控制层代码,先实现全部Recipe数据的获取,新建RecipeController.java:

package indi.nicolashuang.lazymanrecipedemo.controller;

import indi.nicolashuang.lazymanrecipedemo.entity.Recipe;
import indi.nicolashuang.lazymanrecipedemo.service.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/recipe")
public class RecipeController {
    @Autowired
    private RecipeService recipeService;

    @RequestMapping("/getAll")
    @ResponseBody
    public List<Recipe> getAllRecipes(){
        return recipeService.getAll();
    }
}

在service中新建RecipeService.java,注入的RecipeService代码如下,RecipeService类为接口,同目录下新建Impl文件夹,在子文件夹内新建RecipeServiceImpl类继承RecipeService类,算是解耦吧:

import com.mongodb.client.result.UpdateResult;
import indi.nicolashuang.lazymanrecipedemo.entity.Recipe;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public interface RecipeService {
    public List<Recipe> getAll();
}
package indi.nicolashuang.lazymanrecipedemo.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import indi.nicolashuang.lazymanrecipedemo.entity.Recipe;
import indi.nicolashuang.lazymanrecipedemo.service.RecipeService;
import indi.nicolashuang.lazymanrecipedemo.utils.MongodbUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//接口实现
@Service("RecipeService")
public class RecipeServiceImpl implements RecipeService {
    @Autowired
    private MongodbUtils mongodbUtils;

    @Override
    public List<Recipe> getAll(){
        return MongodbUtils.findAll(Recipe.class,"recipe");
    }
}

此处注入的mongodbUtils参考此处。

完成后运行Application,访问http://localhost:8080/recipe/getAll即可显示Recipe的具体内容。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/188332.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ANTLR4入门学习(一)

ANTLR4入门学习&#xff08;一&#xff09;一、安装Antlr1.1 环境1.2 安装命令1.3 校验安装1.4 自定义脚本二、简单使用2.1 加入Hello parrt语法文件2.2 加入调试工具TestRig2.3 开始调试-tokens选项&#xff0c;会打印出全部的词法符号的列表-tree会打印出LISP风格文本格式的语…

ICG试剂 ICG-PEG-NHS_ICG-PEG-SE_吲哚菁青-聚乙二醇-活性酯

【中文名称】吲哚菁青-聚乙二醇-活性酯&#xff0c;吲哚菁绿琥珀酰亚胺脂【英文名称】 ICG-PEG-NHS&#xff0c;ICG-PEG-SE&#xff0c;ICG-PEG-NHS ester【光谱图】【CAS号】N/A【分子量】400、600、1000、2000、3400、5000、10000、20000【纯度标准】95%【包装规格】5mg&…

Java 删除链表中的节点

删除链表中的节点中等有一个单链表的 head&#xff0c;我们想删除它其中的一个节点 node。给你一个需要删除的节点 node 。你将 无法访问 第一个节点 head。链表的所有值都是 唯一的&#xff0c;并且保证给定的节点 node 不是链表中的最后一个节点。删除给定的节点。注意&#…

50.Isaac教程--基于Elbrus立体视觉 VSLAM 的定位

基于Elbrus立体视觉 VSLAM 的定位 ISAAC教程合集地址: https://blog.csdn.net/kunhe0512/category_12163211.html 文章目录基于Elbrus立体视觉 VSLAM 的定位架构嵌入式高保真嵌入式降噪惯性测量单元 (IMU) 集成SLAM 与纯视觉里程计使用立体相机示例应用程序源代码在 x86_64 主机…

代码随想录算法训练营第十四天 | 层序遍历 10,226.翻转二叉树,101.对称二叉树 2

一、参考资料层序遍历 10题目链接/文章讲解/视频讲解&#xff1a;https://programmercarl.com/0102.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86.html翻转二叉树 &#xff08;优先掌握递归&#xff09;题目链接/文章讲解/视频讲解&#xff1a;h…

项目看板开发经验分享(三)——电子车间能源监控看板(渐变色环形进度条、按钮控制展示折线图项、看板表格设计与单击双击事件)

系列完结篇&#xff0c;直奔主题 电子车间能源监控看板展示视频1、渐变色环形进度条 在进度条下方直接加svg实现&#xff0c;中间的字体则先隐藏环形进度条默认的文字:show-text"false"&#xff0c;再用绝对定位来写进去 <div class"ball_bg"><el…

RestTemplate 以及 WebClient 调用第三方接口使用总结

title: RestTemplate 以及 WebClient 调用第三方接口使用总结 date: 2023-01-31 16:51:29 tags: 开发技术及框架 categories:开发技术及框架 cover: https://cover.png feature: false 1. RestTemplate 1.1 引入依赖 RestTemplate 在 spring-boot-starter-web 包下 <dep…

HashMap和HashSet

目录 1、认识 HashMap 和 HashSet 2、哈希表 2.1 什么是哈希表 2.2 哈希冲突 2.2.1 概念 2.2.2 设计合理哈希函数 - 避免冲突 2.2.3 调节负载因子 - 避免冲突 2.2.4 Java中解决哈希冲突 - 开散列/哈希桶 3、HashMap 的部分源码解读 3.1 HashMap 的构造方法 3.2 Hash…

使用CURL快速访问MemFire Cloud应用

“超能力”数据库&#xff5e;拿来即用&#xff0c;应用开发人员再也不用为撰写API而发愁。MemFire Cloud 为开发者提供了简单易用的云数据库&#xff08;表编辑器、自动生成API、SQL编辑器、备份恢复、托管运维&#xff09;&#xff0c;很大地降低开发者的使用门槛。 使用curl…

服装行业2023开年现状速递/服装行业的风险及应对方式/有这些特征的服装企业更容易翻身

在刚刚过去的春节假期里&#xff0c;我们经历了近3年最热闹的一次长假&#xff0c;几乎每天都能在街上看到熙熙攘攘的人流。消费者逛街热情呈“井喷式暴涨”&#xff0c;实体店店主的钱包也跟着鼓起来不少&#xff0c;但年后是否能延续这种旺象&#xff1f;服装行业即将迎来全面…

跨境智星速卖通使用常见问题

跨境智星速卖通使用常见问题 Q&#xff1a;如何使用跨境智星批量注册速卖通买家号&#xff1f;需要准备哪些资料 A&#xff1a;需要将注册信息导入到软件里&#xff0c;需要准备邮箱&#xff08;pop/imap协议&#xff09;&#xff0c;IP&#xff0c;地址等信息&#xff0c;将这…

实战excel

实战excel一、Excel数据格式1.1单元格数据类型1.2 数字1.3 文本1.4 日期1.5 单元格格式二、Excel的快捷操作2.1、快捷键大全2.1.1、文件相关2.1.2、通用快捷键2.1.3、表格选择2.1.4、单元格编辑2.1.5、Excel格式化2.1.6、Excel公式2.2 自动插入求和公式2.3 自动进行列差异比对2…

【C++、数据结构】手撕红黑树

文章目录&#x1f4d6; 前言1. 红黑树的概念⚡&#x1f300; 1.2 红黑树的特性&#xff1a;&#x1f300; 1.3 与AVL树的相比&#xff1a;2. 结点的定义&#x1f31f;⭐2.1 Key模型 和 Key_Value模型的引入&#xff1a;&#x1f3c1;2.1.1 K模型&#x1f3c1;2.1.2 KV模型⭐2.2…

架构演进之路

架构设计: 一&#xff1a;如何分层。 1 为什么要分层&#xff1a;分而治之&#xff0c;各施其职&#xff0c;有条不紊。 常见的分层 计算机osi七层&#xff0c;mvc模型分层&#xff0c;领域模型分层。2 单系统分层模型演进 浏览器-->servlrt-->javabean-->db-->渲染…

unity组件LineRenderer

这是一个好玩的组件 主要作用划线&#xff0c;像水果忍者中的刀光&#xff0c;还有一些涂鸦的小游戏&#xff0c;包括让鼠标划线然后让对象进行跟踪导航也可通过此插件完成 附注&#xff1a;unity版本建议使用稳定一些的版本&#xff0c;有些api可能已经发生变化&#xff0c;…

【数据结构初阶】第四篇——双向链表

链表介绍 初始化链表 销毁链表 打印双向链表 查找数据 增加结点 头插 尾插 在指定位置插入 删除结点 头删 尾删 删除指定位置 链表判空 获取链表中元素个数 顺序表和链表对比 存取方式 逻辑结构与物理结构 时间性能 空间性能 链表介绍 本章讲的是带头双向链…

回溯算法秒杀所有排列-组合-子集问题

&#x1f308;&#x1f308;&#x1f604;&#x1f604; 欢迎来到茶色岛独家岛屿&#xff0c;本期将为大家揭晓LeetCode 78. 子集 90. 子集 II 77. 组合 39. 组合总和 40. 组合总和 II 47. 全排列 II&#xff0c;做好准备了么&#xff0c;那么开始吧。 &#x1f332;&#x1f…

上海亚商投顾:A股两市震荡走弱 北证50指数大涨5.8%

上海亚商投顾前言&#xff1a;无惧大盘涨跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。市场情绪沪指今日震荡调整&#xff0c;创业板指午后一度跌近1.5%&#xff0c;黄白二线分化明显&#xff0c;题材概念表现活跃…

Redis快速入门

Redis快速入门&#xff0c;分两个客户端&#xff1a;Jedis和SpringDataRedis 使用Jdedis 1、引入依赖 <!--jedis--> <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.7.0</version>…

python算法面试题

这是我年前做技术面试官&#xff0c;搜集的面试题&#xff0c;从python基础-机器学习-NLP-CV-深度学习框架-Linux-yolo都有一些题目。针对不同方向的应试者问相应方向的问题。 基本上都是面试八股文&#xff0c;收集记录一下&#xff0c;以后自己也会用的到。 面试题 python基…