SpringBoot(入門demo)

以下包含SpringBoot的入門Demo和 SpringBoot+Mybatis的整合入門demo(使用IDE是IDEA)

一、簡介
1、SpringBoot提供一種固定的、約定優(yōu)于配置風格的框架,使開發(fā)者更快地創(chuàng)建基于spring的應用和程序。

2、特性:
1、高效的創(chuàng)建基于spring的應用服務(不是對spring功能的增強,而是提供快速使用spring的方式)
2、鼓勵注解配置
3、為微服務spring cloud鋪路,可整合其他框架(如dubbo thrift等)

3、Spring Boot應用啟動器:
首先pom.xml默認2個模塊:
spring-boot-starter: Spring Boot的核心啟動器,包含了自動配置支持、日志和YAML。
spring-boot-starter-test:測試模塊,包括JUnit、Hamcrest、Mockito
spring-boot-starter-jdbc: 支持JDBC數(shù)據(jù)庫。
spring-boot-starter-thymeleaf: 支持Thymeleaf模板引擎,包括與Spring的集成。
spring-boot-starter-web: 支持全棧式開發(fā),包括Tomcat和Spring-WebMVC。
mybatis-spring-boot-starter: 整合spring-mybatis依賴。


image.png

這些pom依賴為開發(fā)spring應用提供良好的基礎,springboot的第三方庫是比較適合產(chǎn)品開發(fā)的,其中也有些選擇,如日志框架可以用 Logback 或 Log4j,應用服務器可以用 Tomcat 或 Jetty。

4、一些常用的注解:
啟動類常用:
@SpringBootApplication:聲明當前類為SpringBoot入口類,且項目只只能有一個
@RestController:聲明當前類為控制層的類(等價于@Controller+@ResponseBody的結(jié)合,里面的方法都以json格式輸出,不用再寫什么jackjson配置的了)

二、下面是一個最簡單的SpringBoot入門demo:
首先,生成SpringBoot web項目結(jié)構(gòu)有兩種辦法:
1、用Spring initializer
2、用IDEA/Eclipse開放工具構(gòu)建(一般springBoot推薦使用IDEA)

在創(chuàng)建時勾選spring initial,勾選web。
自動生成必要的DemoApplication作為啟動類,對于web項目,也同樣是通過啟動該類,在地址欄輸入映射地址達到訪問目的。


目錄結(jié)構(gòu)

HelloSpringboot.class:

package com.example.demo;

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

@RestController
public class HelloSpringboot {

    @RequestMapping("/hello")
    public String say() {
        System.out.println("Hello springboot");
        return "hello,this is a springboot demo!~";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,@RequestParam("password") String password){
        String result= "username:"+username+",password:"+password;
        System.out.println(result);
         return(result);
    }

}

啟動類DemoApplication.java:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }
}

測試:
啟動啟動類DemoApplication.java,地址欄輸入地址,若頁面顯示返回數(shù)據(jù),則測試成功。

在地址欄輸入:localhost:8080/hello


在地址欄輸入:http://localhost:8080/login?username=tycoding&password=123


三、SpringBoot和Mybatis整合入門Demo
下面是項目整體目錄結(jié)構(gòu):



1、創(chuàng)建項目,選擇spring initial,選擇 web,JDBC,mybatis,mysql,自動生成項目。由于后面用到了junit測試,所以pom.xml中引入junit包(版本要4.12以上)。

2、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 http://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.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

2、使用mysql數(shù)據(jù)庫,創(chuàng)建了表user,創(chuàng)建字段id(bigint) username(varchar(120)) password(varchar(20)) ,插入一些數(shù)據(jù)。

3、application.yml:配置文件,此處注意配置文件一般會自動生成在resource下,先將后綴改為yml(IDEA的自動解析要求所有的xml,yml等文件都放在resource下,且由于springBoot本身是去xml化的,所以一般會寫成yml)
對springboot和jdbc、mybatis等都進行了簡單的配置(此處尤其注意一些配置不能寫錯,在這也出現(xiàn)了不少bug導致研究了很長時間,這是debug的記錄 SpringBoot+Mybatis web項目常見bug

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/smtest?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver

server:
  port: 8080

mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.example.demo.entity

4、entity層:
User.class:

package com.example.demo.entity;

public class User {
    private Long id;
    private String username;
    private String password;

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

5、Mapper層:注意不同于eclipse,IDEA的mapper.xml必須放在resource/mapper下。
UserMapper.java(接口,放在java.com.example.demo.mapper下):

package com.example.demo.mapper;

import com.example.demo.entity.User;
public interface UserMapper {
    
     User findById( Long id);
     
}

UserMapper.xml:(在resource/mapper下):

<?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.demo.mapper.UserMapper">
<resultMap id="userMap" type="com.example.demo.entity.User">
    <id property="id" column="id"/>
    <result property="username" column="username" />
    <result property="password" column="password" />
</resultMap>

<select id="findById" resultMap="userMap">
select * from user where id=#{id}
</select>
</mapper>

6、Service層:訪問mapper
一些注解:
@Service:聲明該類為Service類
@Resource:常常與@Autowired注解替換,聲明為一個bean,@Autowire注解在IDEA中常會引起一些不必要的錯誤,IDEA會無法識別這是一個bean而報警告,此時可用@Resource

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;

    public User findById(Long id){
        return userMapper.findById(id);
    }
}

7、Contoller控制層:
@RestController:聲明該類為控制類。
@RequestMapping:該類/方法的映射地址
@Autowired:聲明bean

UserController:

package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/boot")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUser/{id}")
    public String GetUser(@PathVariable Long id){
        return userService.findById(id).toString();
    }

    @RequestMapping("/find")
    public String findUser(){
        Long id=1000l;
        return userService.findById(id).toString();
    }

    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }
}

8、測試類:
自動生成測試類,用junit測試,idea對著要進行測試的類/方法光標覆蓋 ctrl+shift+t 選擇create test class,勾選要測試的方法。

UserMapper的測試類UserMapperTest:

注意一些注解:
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@Resource
@Test

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
//web項目,junit需要模擬servletContext,所以要加@webAppConfiguration
@WebAppConfiguration
//告訴Junit Spring配置文件
public class UserMapperTest {

    @Resource
    private UserMapper userMapper;

    @Test
    public void findById() throws Exception{
        Long id=1000l;
        User user=userMapper.findById(id);
        System.out.println(user.toString());

    }
}

測試時,只允許測試類的該方法。


以上,是本人初學springboot的基本入門demo,相信只要學過spring以及其他框架的,對于springboot都會比較容易上手,目前,我通過這兩個demo,掌握了一些基本的應用。

對于springboot的學習,不少人都說并沒有必要去買工具書,做demo就會容易上手,對我來說確實如此,但也因此學得不夠系統(tǒng)化,因此之后會不斷鞏固和學習,并記錄下來。

純潔的微笑-SpringBoot,博主寫的挺好的,我本人就是特別不喜歡技術(shù)文章太冗長的,這個還蠻簡明扼要的。但是初學看的時候有一丟丟看不下去,先上手demo之后再嘗試去看就好得多。

此外,在入手過程中,也遇到了不少bug,嘗試了不少解決方案,并記錄了這些bug。
詳閱——SpringBoot+Mybatis web項目常見bug

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。