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

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内容如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.8
         
    
    indi.nicolasHuang
    lazymanrecipedemo
    0.0.1-SNAPSHOT
    lazymanrecipedemo
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


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

暂且添加如此多:

Spring Boot 2 个人App后端实践(1)_第1张图片

2.IDEA连接数据库

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

3.测试页面访问

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

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            org.slf4j
            slf4j-api
        

        
            junit
            junit
            4.12
            compile
        

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




    
    Title


    Hello

同目录可以新建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,作为食谱数据类,参考,此处考虑使用Long型记录时间戳代替时间类型数据,方便处理:

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 getAllRecipes(){
        return recipeService.getAll();
    }
}

在service中新建RecipeService.java,注入的RecipeService代码如下,RecipeService类为接口,同目录下新建Impl文件夹,在子文件夹内新建RecipeServiceImpl类继承RecipeService类(注:Impl类需要注释对应的@Service("XXXService"),不然会提示找不到XXXService导致无法注入),算是解耦吧:

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 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 getAll(){
        return MongodbUtils.findAll(Recipe.class,"recipe");
    }
}

此处注入的mongodbUtils参考此处。

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

你可能感兴趣的:(工作Java学习,spring,boot,数据库,后端,mongodb)