IDEA入门SpringBoot看这一篇就够了,手把手创建工程、开发接口、自定义配置、三层架构实现数据访问

晋俊贤
2023-12-01

idea快速入门SpringBoot

仓库地址:https://gitee.com/baby-gitee/spring-boot-learn.git

1.创建工程

1.1 Spring Initializr

选择SDK:(8)
选择Default
Next

1.2 Project Metadata

Group:输入域名反写(com.XXX)
Artifact:输入项目名(spring-boot-learn)
Type:选择(Maven)
Language:选择语言(Java)
Java Version:选择java版本(8)
Descriptio:描述
Next

1.3 Dependencies

Spring Boot:选择版本(2.2.2)
搜索依赖:输入依赖名(web)
选择(Spring Web)

Next

1.4 选择文件要放置的位置…点击完成

项目结构

入口:SpringBootLearnApplication
配置文件:src/main/java/…/springbootlearn/SpringBootLearnApplication.java
测试入口:src/test/java/com/baby/springbootlearn/SpringBootLearnApplicationTests.java

1.5 修改Pom.xml

version改为想要的springboot版本(2.2.1.RELEASE)

1.5.1 右键Pom.xml文件>Maven>Reimport

idea可能存在bug,刷新后2.2.1.RELEASE报红
如果可以成功运行,则无需理会

解读Pom.xml

spring-boot版本

 <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.2.1.RELEASE</version>
     <relativePath/> <!-- lookup parent from repository -->
 </parent>

项目名称

 <groupId>com.baby</groupId>
 <artifactId>spring-boot-learn</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>spring-boot-learn</name>
 <description>Demo project for Spring Boot</description>

java版本

		<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>
    </dependencies>

插件
Maven项目对于SpringBoot是需要这个插件的

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
运行项目

浏览器访问http://localhost:8080/页面提示Whitelabel Error Page说明启动成功

2.开发接口

com.XXX.springbootlearn下创建包controller
controller包下创建ParaController

创建的Controller必须放在…Application.java同目录下或同目录的子包下
否则会找不到

2.1 编写第一个接口

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 21:01
 */
@RestController
public class ParaController {
    @GetMapping("/firstrequest")
    public  String firstRequest(){
        return "firstRequest";
    }
}

运行项目

浏览器中输入localhost:8080/firstrequest访问
页面显示:firstRequest

2.2 编写获取参数的接口

public class ParaController {
		...
    @GetMapping("/requestpara")
    public  String requestpara(@RequestParam Integer num){
        return "para from request: "+num;
    }
}

运行项目

浏览器中输入localhost:8080/requestpara访问
页面显示:Whitelabel Error Page。。。

浏览器中输入localhost:8080/requestpara?num=5访问
页面显示:para from request: 5

2.3 编写获取路径参数的接口

public class ParaController {
		...
    @GetMapping("/pathpara/{num}")
    public  String pathpara(@PathVariable Integer num){
        return "para from path: "+num;
    }
}

运行项目

浏览器中输入localhost:8080/pathpara/5访问
页面显示:para from path: 5

2.4 统一前缀接口

@RestController
@RequestMapping("pre")
public class ParaController {
    ...
    @GetMapping("/pathpara/{num}")
    public  String pathpara(@PathVariable Integer num){
        return "para from path: "+num;
    }
}

运行项目

浏览器中输入localhost:8080/pre/pathpara/5访问
页面显示:para from path: 5

2.5 多url的用法

@RestController
@RequestMapping("pre")
public class ParaController {
    ...
    @GetMapping({"/multiurl1","/multiurl2"})
    public  String multiurl(@RequestParam Integer num){
        return "multiurl: "+num;
    }
}

运行项目

浏览器中输入localhost:8080/pre/multiurl1?num=5访问
页面显示:multiurl: 5

浏览器中输入localhost:8080/pre/multiurl2?num=5访问
页面显示:multiurl: 5

2.6 传参默认值

@RestController
@RequestMapping("pre")
public class ParaController {
    ...
    @GetMapping("/required")
    public String required(@RequestParam(required = false, defaultValue = "0") Integer num){
        return "para from required: "+num;
    }
}

运行项目

浏览器中输入localhost:8080/pre/required访问
页面显示:para from required: 0

浏览器中输入localhost:8080/pre/multiurl2?num=5访问
页面显示:para from required: 5

3.自定义配置

3.1配置文件

3.1.1 在controller包下创建PropertiesController

package com.baby.springbootlearn.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 22:06
 */
@RestController
public class PropertiesController {
    Integer key1;
    Integer key2;

    @GetMapping("/getValue")
    public String getValue(){
        return "key1="+key1+",key2="+key2;
    }
}

3.1.2 在application.properties

key.key1=3
key.key2=4
运行项目

访问http://localhost:8080/getValue
页面显示:key1=null,key2=null

3.1.3 修改PropertiesController

@RestController
public class PropertiesController {
    @Value("${key.key1}")
    Integer key1;
    @Value("${key.key2}")
    Integer key2;
    ...
}

按住ctrl点击${key1}会跳转到application配置文件,说明绑定成功

运行项目

访问http://localhost:8080/getValue
页面显示:key1=3,key2=4

3.2 配置类

3.2.1 创建config包,在config创建keyConfig配置类

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 22:33
 */
@Component
@ConfigurationProperties(prefix = "key")
public class KeyConfig {
    private Integer key1;
    private Integer key2;

    public Integer getKey1() {
        return key1;
    }

    public void setKey1(Integer key1) {
        this.key1 = key1;
    }

    public Integer getKey2() {
        return key2;
    }

    public void setKey2(Integer key2) {
        this.key2 = key2;
    }
}

必须加上getter和setter
否值无效

3.2.2 在controller创建ConfigController控制器

import com.baby.springbootlearn.config.KeyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 22:38
 */
@RestController
public class ConfigController {
    @Autowired
    KeyConfig keyConfig;

    @GetMapping("/getValuefromconfig")
    public String getValue(){
        return "key1="+keyConfig.getKey1()+",key2="+keyConfig.getKey2();
    }
}

运行项目

访问http://localhost:8080/getValuefromconfig
页面显示:key1=3,key2=4

4.完成三层架构

4.1 在mysql中创建数据库student, 执行以下SQL

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of student
-- ----------------------------
BEGIN;
INSERT INTO `student` VALUES (1, '小明');
INSERT INTO `student` VALUES (2, '小美');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

4.2 在pom.xml中引入依赖:mybatis、mysql驱动

    <dependencies>
        ...
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

4.3 在application.properties中写配置

mysql5.x 使用的驱动是com.mysql.jdbc.Driver
mysql8.x 使用的驱动是com.mysql.cj.jdbc.Driver

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/springbootlearn?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai

4.4 在entity包下创建Student实体

public class Student {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4.5 在dao包下创建StudentMapper

import com.baby.springbootlearn.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 23:18
 */
@Mapper
@Repository
public interface StudentMapper {
    @Select("select id,name from student where id = #{id}")
    Student findById(Integer id);
}

4.6 在service包下创建StudentService服务接口

import com.baby.springbootlearn.entity.Student;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 23:16
 */
public interface StudentService {
    public Student findStudentById(Integer id);
}

4.7 在service.impl包下创建StudentServiceImpl服务接口

import com.baby.springbootlearn.dao.StudentMapper;
import com.baby.springbootlearn.entity.Student;
import com.baby.springbootlearn.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 23:27
 */
@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

    @Override
    public Student findStudentById(Integer id) {
        return studentMapper.findById(id);
    }
}

4.8 在controller包下创建StudentController控制器

import com.baby.springbootlearn.entity.Student;
import com.baby.springbootlearn.service.StudentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

/**
 * @Author: BaBy
 * @Date: 2021/3/7 23:12
 */
@RestController
public class StudentController {
    @Resource
    private StudentService studentService;

    @GetMapping("/student/{id}")
    public String student(@NotNull @PathVariable Integer id){
        Student student = studentService.findStudentById(id);
        return student.toString();
    }
}

运行项目

访问http://localhost:8080/student/1
页面显示:Student{id=1, name=‘小明’}

 类似资料: