美文网首页
Springboot项目搭建

Springboot项目搭建

作者: 南三百里 | 来源:发表于2019-02-24 14:35 被阅读0次

    第一步 新建springboot项目

    通过idea新建项目,选择Spring Initializr,其他可以默认,点击Next即可。

    New Project

    如下图自定义 Group 和 Artifact、选好项目类型,通常使用Maven Project,语言java,打包方式,springboot我选择使用 jar 包方式。

    New Project

    选择几个常用的依赖,后期可根据需要自行添加。

    New Project

    选择项目存储位置。

    New Project

    第二步 添加基本配置文件

    配置数据源、mybatis 和 druid

    1、在pom.xml中添加以下依赖

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

    2、在application.properties中添加数据源及 druid配置如下:

    server.port=8080
    spring.datasource.url=jdbc:mysql://( 填写数据库所在的主机IP ):3306/( 填写数据库名称 )
    spring.datasource.username=username(填写数据库用户名)
    spring.datasource.password=password(填写密码)
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    #druid配置
    spring.datasource.initialSize=5
    spring.datasource.minIdle=5
    spring.datasource.maxActive=20
    spring.datasource.maxWait=60000
    spring.datasource.timeBetweenEvictionRunsMillis=60000
    spring.datasource.minEvictableIdleTimeMillis=300000
    spring.datasource.validationQuery=SELECT 1 FROM DUAL
    spring.datasource.testWhileIdle=true
    spring.datasource.testOnBorrow=false
    spring.datasource.testOnReturn=false
    spring.datasource.poolPreparedStatements=true
    #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    spring.datasource.filters=stat,wall,logback
    spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
    spring.datasource.useGlobalDataSourceStat=true
    spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    #spring.datasource.schema=sql文件路径,可以直接建表
    #mybatis 配置
    mybatis.config-location=classpath:mybatis-config.xml
    mybatis.mapper-locations=classpath:com/example/demo/**/*Mapper.xml
    

    也可以是yml格式的:

    server:
      port: 8080
    spring:
      datasource:
        username: username
        password: password
        url: jdbc:mysql://( 填写你的数据库所在主机ip ):3306/( 填写数据名称 )
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
        #   数据源其他配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall,logback
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
        # schema:
        # - classpath:sql/user.sql
    
    # mybatis 配置
    mybatis:
      config-location: classpath:mybatis-config.xml
      mapper-locations: classpath:com/example/demo/**/*Mapper.xml
    

    3、在 resources 文件夹下新建 mybatis-config.xml,内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <settings>
            <setting name="cacheEnabled" value="true"/>
            <setting name="lazyLoadingEnabled" value="false"/>
            <setting name="aggressiveLazyLoading" value="false"/>
            <setting name="multipleResultSetsEnabled" value="true"/>
            <setting name="useColumnLabel" value="true"/>
            <setting name="useGeneratedKeys" value="true"/>
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <setting name="autoMappingBehavior" value="PARTIAL"/>
            <setting name="defaultExecutorType" value="REUSE"/>
            <setting name="defaultStatementTimeout" value="25000"/>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <setting name="callSettersOnNulls" value="true"/>
        </settings>
    
    </configuration>
    

    4、在 pom.xml 中添加 mybatis.generator 插件,可以根据generatorConfig.xml配置文件生成 mybatis 映射、model层、dao层和 mapper层。

    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <configuration>
            <verbose>true</verbose>
            <overwrite>true</overwrite>
        </configuration>
    </plugin>
    

    generatorConfig.xml配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
        <!-- 配置mysql 驱动jar包路径.用了绝对路径 -->
        <classPathEntry location="C:\Users\JingXi\.m2\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>
    
        <context id="wangyongzhi_mysql_tables" targetRuntime="MyBatis3">
            <!-- 防止生成的代码中有很多注释,加入下面的配置控制 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true" />
                <property name="suppressDate" value="true" />
            </commentGenerator>
    
            <!-- 数据库连接 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://192.168.31.128:3306/copyrightblock?useUnicode=true;characterEncoding=UTF-8"
                            userId="copyrightblock"
                            password="123456">
            </jdbcConnection>
    
            <javaTypeResolver >
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
    
            <!-- 数据表对应的model层  -->
            <javaModelGenerator targetPackage="com.example.demo.model" targetProject="src">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
    
            <!-- sql mapper 映射配置文件 -->
            <sqlMapGenerator targetPackage="com.example.demo.mapper"  targetProject="src">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
    
            <!-- mybatis3中的mapper接口 -->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.dao"  targetProject="src">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
    
            <!-- 数据表进行生成操作 schema:相当于库名; tableName:表名; domainObjectName:对应的DO -->
            <table schema="test" tableName="test_user" domainObjectName="TestUser"
                   enableCountByExample="false" enableUpdateByExample="false"
                   enableDeleteByExample="false" enableSelectByExample="false"
                   selectByExampleQueryId="false">
            </table>
    
        </context>
    </generatorConfiguration>
    

    注意classPathEntry location的路径,配置好后可以运行插件即可生成三层结构,之后自行追加 service和 serviceimp。

    注意:要在主类DemoApplication中添加注解@MapperScan扫描到 dao层接口。

    package com.example.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan(basePackages = "com.example.demo.dao")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    
    

    出现 target中没有 mapper.xml解决办法,在pom.xml中的 built 中插入下面配置

        <resources>
          <!-- mapper.xml文件在java目录下 -->
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.xml</include>
            </includes>
          </resource>
        </resources>
    

    druid的管理界面,需要添加一个 DruidConfig.java类:

    package com.example.demo.common.druidconfig;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.sql.DataSource;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * Author: Jankin
     * Date:2019/2/21
     * Description:
     */
    @Configuration
    public class DruidConfig {
    
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druid(){
            return  new DruidDataSource();
        }
    
        //配置Druid的监控
        //1、配置一个管理后台的Servlet
        @Bean
        public ServletRegistrationBean statViewServlet(){
            ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
            Map<String,String> initParams = new HashMap<>();
    
            initParams.put("loginUsername","admin");
            initParams.put("loginPassword","123456");
            initParams.put("allow","");//默认就是允许所有访问
            initParams.put("deny","192.168.15.21");
    
            bean.setInitParameters(initParams);
            return bean;
        }
    
    
        //2、配置一个web监控的filter
        @Bean
        public FilterRegistrationBean webStatFilter(){
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.setFilter(new WebStatFilter());
    
            Map<String,String> initParams = new HashMap<>();
            initParams.put("exclusions","*.js,*.css,/druid/*");
    
            bean.setInitParameters(initParams);
    
            bean.setUrlPatterns(Arrays.asList("/*"));
    
            return  bean;
        }
    }
    
    

    启动项目后访问http://localhost:8080/druid/# 可以进入以下界面:

    New Project

    输入配置的账号密码后进入界面

    New Project

    第三步 可以写代码了

    补充建表sql文件,在运行mybatis.generator插件之前先把表建好

    CREATE TABLE ttai_user (
        id BIGINT NOT NULL auto_increment COMMENT '主键id',
        user_account VARCHAR(20) NOT NULL COMMENT '用户账号',
        user_pwd VARCHAR(50) NOT NULL COMMENT '账号id表,新注册用户的record_id',
        user_nickname VARCHAR(50) NOT NULL COMMENT '用户',
        user_email VARCHAR(320) NOT NULL COMMENT '用户邮箱地址',
        del_sign INT NOT NULL DEFAULT 0 COMMENT '0:未删除 1:已删除',
        create_tx_stamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
        lastup_tx_stamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
        PRIMARY KEY ( id )
    );
    

    写了个小接口:

    package com.example.demo.controller;
    
    import com.example.demo.common.Result;
    import com.example.demo.model.TtaiUser;
    import com.example.demo.service.TtaiUserService;
    import com.google.gson.Gson;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * Author: Jankin
     * Date:2019/2/21
     * Description:
     */
    @RestController
    public class TestContrller {
    
        private final TtaiUserService ttaiUserService;
    
        @Autowired
        public TestContrller(TtaiUserService ttaiUserService) {
            this.ttaiUserService = ttaiUserService;
        }
    
        @PostMapping("/test")
        public String add(@RequestParam("account") String account,
                          @RequestParam("pwd") String pwd){
            TtaiUser user = new TtaiUser();
            user.setUserAccount(account);
            user.setUserPwd(pwd);
            user.setUserNickname("null");
            user.setUserEmail("null");
            this.ttaiUserService.insertSelective(user);
            return new Gson().toJson(new Result());
        }
    }
    
    

    成功运行

    New Project

    发起一个post请求看看效果:

    New Project
    New Project

    不小心点了两次没有做用户名唯一性校验,所以插入了两条一样的数据。

    原文链接https://zzjing.top/2019/02/21/springboot%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA/

    这是项目地址https://github.com/jingxizhu/springbootbuild

    下回分享使用通用mapper~

    相关文章

      网友评论

          本文标题:Springboot项目搭建

          本文链接:https://www.haomeiwen.com/subject/tqtbyqtx.html