SpringBoot框架搭建详细教程【附源码及下载地址】

目录

【开发环境】

一、【新建项目】

二、【目录结构调整】

三、【maven包初始化】

四、【springboot和mybatis配置】

五、【Demo构建】


项目源码下载地址:https://gitee.com/liwenchao_jack/springboot.git


【开发环境】

1.操作系统:windows

2.开发工具:IDEA

3.java -version

一、【新建项目】

File→New Project→Spring Initializr,选择下一步

添加组织信息,然后下一步

选择SQL→Mybatis Framework,然后下一步

点击finish

项目创建完毕,目录结构如下,可以对目录结构做个优化,删除标红部分。

二、【目录结构调整】

修改src-main-java下的文件名为cn.com.springboot

项目完整目录结构:

- Java为主Java代码文件夹

  - Controller 控制器文件文件夹

  - Dao (数据访问)层文件夹

  - Service(业务逻辑)层文件夹

  - Entity(实体)层文件 

- resources资源文件夹

  - mapper mybatis文件夹

     - sql 数据表文件夹

- Test 测试文件夹

三、【maven包初始化】

Maven是采用配置文件的方式进行jar包的自动导入。下面添加我们将会用到的一系列jar包配置:

<?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>

    <groupId>cn.com.springboot</groupId>
    <artifactId>springboot_test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot_test</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>cn.com.springboot.SpringbootTestApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

等待jar包下载到本地默认仓库,maven导入阶段完成,我们就可以进行下一步了。如果jar包不能正常导入,可以有下面处理办法:从这个地址:https://mvnrepository.com/;下载对应的jar包。然后查看本地是否安装了maven:

win+R快捷键,然后输入cmd,最后输入mvn -v;这里我已经配置好了,没有配置的自行百度。

通过命令安装jar包:

示例:mvn install:install-file -DgroupId=org.mybatis.generator -DartifactId=mybatis-generator-core -Dversion=1.3.5 -Dpackaging=jar -Dfile=D:\mybatis-generator-core-1.3.5.jar

-DgroupId、-DartifactId、 -Dversion可以参看我们pom里的jar包依赖修改,-Dfile是你下载下来的那个jar的本地目录,其他无需更改。

四、【springboot和mybatis配置】

配置文件包含:application.properties、logback-spring.xml、banner.txt

配置application.properties

mybatis.typeAliasesPackage=cn.com.springboot.entity
mybatis.mapperLocations=classpath:mapper/*.xml

# DataSouce
spring.datasource.url=jdbc:mysql://192.168.1.91:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-wait=10000
spring.datasource.min-idle=2
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.maxActive=10
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.filters=stat

配置logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="false" scanPeriod="1 minutes">
    <property name="APP_NAME" value="tradeareadatapush-job"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender" >
        <encoder>
            <pattern>%d{yyyy-MM-dd.HH:mm:ss.SSS} %t %p %c{0} %X{traceId} : %m%n</pattern>
        </encoder>
    </appender>

    <root level="INFO" >
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

springboot在启动的时候有一个banner图,我们在这里可以实现自定义,banner.txt文件中存放的就是新的banner图。我们可以在线制作banner图,在线地址:http://patorjk.com/software/taag/#p=display&f=Henry%203D&t=spring%0A

我们创建的banner-springboot_test如下:


                               __                        _                            _                _                          _
    ____     _ ___     _ ___   LJ   _ ___      ___ _    FJ___      ____      ____    FJ_              FJ_      ____      ____    FJ_
   F ___J   J '__ J   J '__ ",     J '__ J    F __` L  J  __ J    F __ J    F __ J  J  _|            J  _|    F __ J    F ___J  J  _|
  | '----_  | |--| |  | |__|-J FJ  | |__| |  | |--| |  | |--| |  | |--| |  | |--| | | |-'            | |-'   | _____J  | '----_ | |-'
  )-____  L F L__J J  F L  `-'J  L F L  J J  F L__J J  F L__J J  F L__J J  F L__J J F |__-.          F |__-. F L___--. )-____  LF |__-.
 J\______/FJ  _____/LJ__L     J__LJ__L  J__L )-____  LJ__,____/LJ\______/FJ\______/F\_____/ ________ \_____/J\______/FJ\______/F\_____/
  J______F |_J_____F |__L     |__||__L  J__|J\______/FJ__,____F  J______F  J______F J_____F|________|J_____F J______F  J______F J_____F
           L_J                               J______F                                      L________J

五、【Demo构建】

打开数据库,执行以下脚本

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `test`.`student` (`id`, `name`, `age`, `sex`, `address`) VALUES ('1', '张三', '18', '1', '北京市朝阳区');
INSERT INTO `test`.`student` (`id`, `name`, `age`, `sex`, `address`) VALUES ('2', '王五', '20', '1', '天津市南开区');
INSERT INTO `test`.`student` (`id`, `name`, `age`, `sex`, `address`) VALUES ('3', '李丽', '22', '0', '上海市虹桥区');

下面我们从entity→mapper→dao→servive→SpringbootTestApplication来构建

编写entity:Student

package cn.com.springboot.entity;

public class Student {
    private int id;
    private String name;
    private int age;
    private int sex;
    private String address;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}

编写mapper:UserMapper.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="cn.com.springboot.dao.StudentDao" >
    <resultMap id="resultMap" type="cn.com.springboot.entity.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>
    </resultMap>

    <sql id="columnSql">
        <trim suffixOverrides=",">
            t.id,
            t.name,
            t.age,
            t.sex,
            t.address
        </trim>
    </sql>
    <select id="listStudentInfo" resultType="cn.com.springboot.entity.Student">
        SELECT
        <include refid="columnSql"/>
        FROM student t
    </select>
</mapper>

编写dao:StudentDao

package cn.com.springboot.dao;

import cn.com.springboot.entity.Student;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentDao {
    List<Student> listStudentInfo();
}

编写Service:StudentService

package cn.com.springboot.service;

public interface IStudentService {
    void datapush();
}

StudentServiceImpl

package cn.com.springboot.service.impl;

import cn.com.springboot.dao.StudentDao;
import cn.com.springboot.entity.Student;
import cn.com.springboot.service.IStudentService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements IStudentService {
    private static Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Autowired
    private StudentDao studentDao;

    @Override
    public void datapush() {
        logger.info("-------------学生信息数据推送任务开始执行-------------");
        List<Student> students = studentDao.listStudentInfo();
        ObjectMapper objectMapper = new ObjectMapper();
        String result = null;
        try {
            result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(students);
            logger.info("学生信息数据:\n" + result);
        } catch (JsonProcessingException e) {
            logger.error("数据转换异常[List to Json]", e);
        }

        // 模拟http post 推送数据到其它数据服务
        try {
            Thread.sleep(1000);
            logger.info("数据推送成功!");
        } catch (InterruptedException e) {
            logger.error("服务异常!", e);
        }
    }
}

编写SpringbootTestApplication

package cn.com.springboot;

import cn.com.springboot.service.IStudentService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@MapperScan("cn.com.springboot.dao")
public class SpringbootTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTestApplication.class, args);
    }

    @Autowired
    private IStudentService studentService;

    @Bean
    public String starter(){
        studentService.datapush();
        return "success";
    }

}

完整目录如下:

启动springboot项目

控制台打印日志:

Connected to the target VM, address: '127.0.0.1:53743', transport: 'socket'

                               __                        _                            _                _                          _
    ____     _ ___     _ ___   LJ   _ ___      ___ _    FJ___      ____      ____    FJ_              FJ_      ____      ____    FJ_
   F ___J   J '__ J   J '__ ",     J '__ J    F __` L  J  __ J    F __ J    F __ J  J  _|            J  _|    F __ J    F ___J  J  _|
  | '----_  | |--| |  | |__|-J FJ  | |__| |  | |--| |  | |--| |  | |--| |  | |--| | | |-'            | |-'   | _____J  | '----_ | |-'
  )-____  L F L__J J  F L  `-'J  L F L  J J  F L__J J  F L__J J  F L__J J  F L__J J F |__-.          F |__-. F L___--. )-____  LF |__-.
 J\______/FJ  _____/LJ__L     J__LJ__L  J__L )-____  LJ__,____/LJ\______/FJ\______/F\_____/ ________ \_____/J\______/FJ\______/F\_____/
  J______F |_J_____F |__L     |__||__L  J__|J\______/FJ__,____F  J______F  J______F J_____F|________|J_____F J______F  J______F J_____F
           L_J                               J______F                                      L________J

2019-07-22.16:05:15.229 main INFO SpringbootTestApplication  : Starting SpringbootTestApplication on 1JL9XBNQI6KJHVC with PID 9972 (D:\workspace\workspace3\springboot_test\target\classes started by liwc in D:\workspace\workspace3\springboot_test)
2019-07-22.16:05:15.239 main INFO SpringbootTestApplication  : No active profile set, falling back to default profiles: default
2019-07-22.16:05:16.879 main INFO StudentServiceImpl  : -------------学生信息数据推送任务开始执行-------------
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-07-22.16:05:17.199 main INFO DruidDataSource  : {dataSource-1} inited
2019-07-22.16:05:17.969 main INFO StudentServiceImpl  : 学生信息数据:
[ {
  "id" : 1,
  "name" : "张三",
  "age" : 18,
  "sex" : 1,
  "address" : "北京市朝阳区"
}, {
  "id" : 2,
  "name" : "王五",
  "age" : 20,
  "sex" : 1,
  "address" : "天津市南开区"
}, {
  "id" : 3,
  "name" : "李丽",
  "age" : 22,
  "sex" : 0,
  "address" : "上海市虹桥区"
} ]
2019-07-22.16:05:18.969 main INFO StudentServiceImpl  : 数据推送成功!
2019-07-22.16:05:19.229 main INFO SpringbootTestApplication  : Started SpringbootTestApplication in 4.65 seconds (JVM running for 5.953)
2019-07-22.16:05:19.239 Thread-10 INFO DruidDataSource  : {dataSource-1} closed
Disconnected from the target VM, address: '127.0.0.1:53743', transport: 'socket'

Process finished with exit code 0

至此,springboot-mybatis框架搭建完毕,如果想添加web进来,可以继续扩展。


项目源码下载地址:https://gitee.com/liwenchao_jack/springboot.git


演示结束,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值