IDEA开发环境搭建、初始化SpringBoot项目(SSM、swagger、lombook)与IDEA常用快捷键指南

@IDEA开发环境搭建、初始化SpringBoot项目(SSM)与IDEA常用快捷键指南

1、IDEA本地开发环境搭建

你好! 这是最近学习使用IDEA工具的一篇学习汇总哈,本篇总结一些搭建环境的步骤以及开发时的常用快捷键,方便入手学习 。

下载官网最新的IDEA(社区版Community)

官网下载地址(idea/windows): www.jetbrains.com

  1. Version: 2019.3.3 ,如图点击下载即可;
    在这里插入图片描述
  2. 此处省略安装过程;

2、初始化SpringBoot项目(SSM、lombook)

1.快捷方式新建SpringBoot项目
工具栏“File” --> “New”–>“Project”–> 选择"Spring Assistant",点击 "Next"按钮
注: "Spring Assistant"插件,我这安装后默认是没有的。
安装步骤
在settings -> Plugins 里边搜Spring Assistant,安装完后重启idea即可。
在这里插入图片描述
2.点击下一步后,可以修改“Group Id” 、“Artifact Id”、“Packageing”等
在这里插入图片描述
3.选择需要的插件(后续如果有使用的pom修改后加即可)
在这里插入图片描述
4.多环境配置,删除默认自带的application.properties,新建文件如图。【蓝框部分】(根据自己的喜好哈)
在这里插入图片描述
application.yml

# application-dev.yml:开发环境
# application-test.yml:测试环境
# application-prod.yml:生产环境
spring:
  profiles:
    active: test

application-dev.yml
注: ssl下是https证书相关的配置,需要的可以放开下。

# server
server:
  port: 8091
  #ssl:
    #protocol: TLS
    # 证书位置
    #key-store: classpath:xxxxx.jks
    # 证书密码
    #key-store-password: xxxxxx
    # 证书类型
    #key-store-type: JKS
    # 证书别名
    #key-alias: xxxxxx

# spring
spring:
  datasource:
    username: xxxxxx
    password: xxxxxx
    url: jdbc:mysql://localhost:3306/xxxxxx?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis
mybatis:
  mapper-locations: classpath:sqlmap/*Mapper.xml
  type-aliases-package: com.xxxx.xxxx.entity

# logging
logging:
  path: /opt/server/log/
  file: server.log
  level:
    root: INFO
    com:
      xxxx:
        xxxx:
          mapper: debug

已下文件同理application-dev.yml 此处就不细说了。
#application-test.yml:测试环境
#application-prod.yml:生产环境

5.关于mybatis逆向生成的配置。【红框部分】
在这里插入图片描述
generatorConfig.xml
中 需要替换mysql驱动的物理目录,把路径换成自己的。

<?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>
    <!--导入属性配置 -->
    <properties resource="generator.properties"/>
    <!-- 把路径换成自己的 -->
    <classPathEntry
            location="D:\Program Files\apache-maven-3.6.0\repository\mysql\mysql-connector-java\8.0.19\mysql-connector-java-8.0.19.jar" />
    <context id="context1">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}" />

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}"
                            targetProject="${modelProject}" />
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
        <javaClientGenerator targetPackage="${mapperPackage}"
                             targetProject="${mapperProject}" type="XMLMAPPER" />

        <!-- 如果需要通配所有表 直接用sql的通配符    %即可 -->
        <table schema="" tableName="${table}" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"

        >
            <!--<columnOverride column="REMARKS" javaType="java.lang.String" jdbcType="VARCHAR"/>-->
        </table>

    </context>
</generatorConfiguration>

generator.properties
中xxxxxxx 为需要替换的配置。

#基本信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://xxxxxxx:3306/xxxxxxx?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username=xxxxxxx
password=xxxxxxx

#entity 包名和 java目录
modelPackage=com.xxxxxxx.xxxxxxx.entity
modelProject=src/main/java

#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources

#mapper包名和 java目录
mapperPackage=com.xxxxxxx.xxxxxxx.mapper
mapperProject=src/main/java


table=xxxxxxx

pom.xml 增加插件
中 注意入口类目录的替换mainClass

<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<mainClass>com.xxxx.xxxx.demoApplication</mainClass>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<!--mybatis-generator-->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
					<overwrite>true</overwrite>
					<verbose>true</verbose>
				</configuration>
			</plugin>
			<!-- 打包过程忽略Junit测试 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>

验证

a、直接插件验证下配置是否生效
在这里插入图片描述
b、控制台查看下生成的文件名字。
在这里插入图片描述
c、点击项目名 右击–> Reload from Disk 按钮即可。
PS: 此处mybatis逆向生成mapper的接口、参数实体类和mapper对应的xml 。

d、编写service层以及controller层
此处直接上代码示例
com.xxx.xxxx.service下 XxxxxxxxxService.java

package com.xxxx.xxxx.service;

import com.xxxx.xxxx.entity.TestEntity;

/**
 *
 * @author xxxxx
 * @description XxxxxxxxxService
 * @date 2020/3/12
 */
public interface XxxxxxxxxService{

    public int deleteByPrimaryKey(Long roomId);

    public int insert(TestEntity record);

    public int insertSelective(TestEntity record);

    public TestEntity selectByPrimaryKey(Long roomId);

    public int updateByPrimaryKeySelective(TestEntity record);

    public int updateByPrimaryKey(TestEntity record);
}

com.xxx.xxxx.service.impl 下 XxxxxxxxxServiceImpl .java

package com.xxxx.xxxx.service.impl;

import com.xxxx.xxxx.entity.TestEntity;
import com.xxxx.xxxx.mapper.XxxxxxMapper;
import com.xxxx.xxxx.service.xxxxxxxxxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author xxxxxxxxx
 * @description XxxxxxxxxServiceImpl 
 * @date 2020/3/12
 */
@Service
public class XxxxxxxxxServiceImpl implements XxxxxxxxxService {

    @Autowired
    XxxxxxMapper xxxxxxMapper ;

    @Override
    public int deleteByPrimaryKey(Long roomId) {
        return xxxxxxMapper.deleteByPrimaryKey(roomId);
    }

    @Override
    public int insert(TestEntity record) {
        int flag= 0;
        try {
            flag = xxxxxxMapper.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public int insertSelective(TestEntity record) {
        return xxxxxxMapper.insert(record);
    }

    @Override
    public TestEntity selectByPrimaryKey(Long roomId) {
        TestEntity testEntity = null;
        try {
            testEntity =  xxxxxxMapper.selectByPrimaryKey(roomId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return testEntity;
    }

    @Override
    public int updateByPrimaryKeySelective(TestEntity record) {
        return xxxxxxMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(TestEntity record) {
        return xxxxxxMapper.updateByPrimaryKey(record);
    }
}

com.xxx.xxxx.controller 下 XxxxxxController.java

package com.xxx.xxxx.controller;

import com.xxx.xxxx.entity.TestEntity;
import com.xxx.xxxx.service.impl.XxxxxxxxxServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * XxxxxxController
 * @author xxxxxx
 * @date 2020/3/1
 */
@RequestMapping("/api/v1.0/xxxxxxxxx")
@RestController
@Api(value = "Test API", tags = "test", description = "test相关接口")
public class XxxxxxController {
    private static final Logger logger = LoggerFactory.getLogger(XxxxxxController.class);

    @Autowired
    XxxxxxxxxServiceImpl xxxxxxxxxServiceImpl ;

    /**
     * selectByPrimaryKey
     * @author xxxxxx
     * @date 2020/3/2
     * @param record
     * @return TestEntity
     */
    @ApiOperation(value = "测试selectByPrimaryKey", notes = "测试selectByPrimaryKey")
    @PostMapping(("/selectByPrimaryKey"))
    public TestEntity selectByPrimaryKey(@RequestBody TestEntity record){
        return  xxxxxxxxxServiceImpl.selectByPrimaryKey(record.getRoomId());
    }

    /**
     * insert
     * @author xxxxxx
     * @date 2020/3/2
     * @param record
     * @return TestEntity
     */
    @ApiOperation(value = "测试insert", notes = "测试insert")
    @PostMapping(("/insert"))
    public int insert(@RequestBody TestEntity record){
        return xxxxxxxxxServiceImpl.insert(record);
    }
}

接下来启动项目测试下CRUD了,右击 xxxxApplication.java run即可。
在这里插入图片描述
请求地址例如,此处使用postman 软件
http://localhost:8091/api/v1.0/xxxxxxxxx/selectByPrimaryKey
http json post 请求即可。
{“roomId”: 5649088893768748}

在这里插入图片描述
6、日志拦截器(打印公共出入参)
LogRecordAspect.java

package com.xxxx.xxxx.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author xxxx
 * @description LogRecordAspect
 * @date 2020/3/1
 */
@Aspect
@Configuration//定义一个切面
public class LogRecordAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.xxxx.xxxx.controller..*.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        Object[] args = pjp.getArgs();
        String params = "";
        //获取请求参数集合并进行遍历拼接
        if(args.length>0){
            if("POST".equals(method)){
                Object object = args[0];
                Map map = getKeyAndValue(object);
                params = JSON.toJSONString(map);
                ;
            }else if("GET".equals(method)){
                params = queryString;
            }
        }


        logger.info("请求开始===地址:"+url);
        logger.info("请求开始===类型:"+method);
        logger.info("请求开始===参数:"+params);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        logger.info("请求结束===返回值:" + JSON.toJSONString(result));
        return result;
    }

    public static Map<String, Object> getKeyAndValue(Object obj) {
        Map<String, Object> map = new HashMap<>();
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            Object val = new Object();
            try {
                val = f.get(obj);
                // 得到此属性的值
                map.put(f.getName(), val);// 设置键值
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return map;
    }
}

7、swagger自动生成接口文档
SwaggerProperties.java 此配置类依赖yaml 中的新增配置

package com.xxxx.xxxx.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class SwaggerProperties {
    /**
     * contactName
     */
    @Value("${swagger.contact-name}")
    private String contactName;

    /**
     * contactEmail
     */
    @Value("${swagger.contact-email}")
    private String contactEmail;

    /**
     * contactUrl
     */
    @Value("${swagger.contact-url}")
    private String contactUrl;

    /**
     * groupName
     */
    @Value("${swagger.group-name}")
    private String groupName;
}

application-dev.yml

# swagger
swagger:
  contact-name: xxxxxx
  contact-email: xxxxxx@163.com
  contact-url: http://localhost:8091/swagger-ui.html
  group-name: xxxxxx

SwaggerConfig.java

package com.xxxx.xxxx.swagger;

import com.xxxx.xxxx.config.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author xxxx
 * @description SwaggerConfig
 * @date 2020/3/1
 */
//@Profile 注解 标识加载在dev和test文件使用
@Profile({"dev", "test"})
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    SwaggerProperties swaggerProperties;

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(swaggerProperties.getGroupName())
                .apiInfo(getApiInfo())
                .select()
                //设置basePackage会将包下的所有被@Api标记类的所有方法作为api
                .apis(RequestHandlerSelectors.basePackage("com.xxxx.xxxx.controller"))
                //只有标记了@ApiOperation的方法才会暴露出给swagger
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.regex("/api/.*")).build();
    }

    private ApiInfo getApiInfo(){
        Contact contact = new Contact();
        contact.setName(swaggerProperties.getContactName());
        contact.setEmail(swaggerProperties.getContactEmail());
        contact.setUrl(swaggerProperties.getContactUrl());
        return new ApiInfoBuilder()
                .title("API接口文档")
                .description("swagger2 "+ swaggerProperties.getGroupName() +" api")
                .termsOfServiceUrl(swaggerProperties.getContactUrl())
                .version("1.0")
                .contact(contact.toString())
                .build();
    }
}

加入后并在启动入口类添加
@EnableSwagger2 切记
在这里插入图片描述
swagger地址
http://localhost:8091/swagger-ui.html

8.因为后期增加了 一些功能
(日志切面、swagger2、RestTemplate等实用功能),直接上我配置的做参考,

<dependencies>
		<!--spring-boot-starter-web-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--spring-boot-starter-jdbc-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!--mybatis-spring-boot-starter-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.1</version>
		</dependency>
		<!--mysql-connector-java-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!--spring-boot-starter-test-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!--spring-boot-starter-aop-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>
		<!--lombok-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.10</version>
		</dependency>
		<!--httpclient-->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>
		<!--fastjson-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>LATEST</version>
		</dependency>
		<!--swagger2-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
	</dependencies>

3、IDEA常用快捷键指南

删除当前空行:Ctrl + Y
移动一行代码:Ctrl+ Shift + 箭头↑/↓
查找:Ctrl/ + F

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值