介绍
鉴于很多新手对mac下的idea开发工具创建springboot项目不太了解,今天抽了点时间,重新整理了个mac系统下创建springboot项目的详细经过,接下来直接进入正题。
创建
1、打开已安装的idea开发工具,点击 Create new project
image2、左边选择Srping Initializr,然后右边保持默认,如果jdk安装了多个,注意选择对应的版本,这里我的是1.8
image3、分别填写Group、Artifact、Type、Java Version等字段,Type项选择Maven POM是因为后面我们要采用多模块形式开发管理,这里这个作为父工程
image4、选择Spring Boot版本,这里我选的是2.3.11,建议不要选太高版本,然后勾选所需要的依赖库,点Next
image5、选择项目存放的路径,点Finish
image6、一个简单的父工程项目结构如图
image7、接下来开始创建子模块,选择顶部菜单栏中菜单 File -> New -> Module
image8、左边依然选择Spring Initializr,然后点Next
image9、填写Group、Artifact、Java Version等字段,Type项选择Maven Project
image10、选择Spring Boot 版本为2.3.11,分别勾选依赖,如下图,点击Next
image11、点击 Finish完成创建
image集成
1、父工程中pom.xml 中添加swagger的依赖
image2、调整manager工程的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yans.sb</groupId> <!-- 父工程的 groupId -->
<artifactId>springboot</artifactId><!-- 父工程的 artifactId -->
<version>0.0.1-SNAPSHOT</version><!-- 父工程的 version -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yans.sb</groupId>
<artifactId>manager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>manager</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 这里只添加当前子工程所需的依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- mysql -->
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--线程池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、接下来在manager中的src目录下创建对应的文件目录和代码文件,结构如图
13.png
对应的文件内容如下:
- DataSourceConfiguration
package com.yans.sb.manager.config.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;
/**
* 数据库配置类
*/
@Configuration
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSouce")
public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
//关闭连接后不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
- SessionFactoryConfiguration
package com.yans.sb.manager.config.dao;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
/**
* 数据库sqlSession配置类
*/
@Configuration
public class SessionFactoryConfiguration {
@Value("${mapper_path}")
private String mapperPath;
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
@Autowired
private DataSource dataSouce;
@Value("${entity_package}")
private String entityPackage;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setDataSource(dataSouce);
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}
- TransactionManagementConfiguration
package com.yans.sb.manager.config.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
/**
* 事务配置类,不可缺少,尚未知具体作用
*/
@Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer{
@Autowired
private DataSource dataSource;
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
- Swagger2
package com.yans.sb.manager.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yans.sb.manager"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot平台")
.description("介绍")
.version("4.0")
.termsOfServiceUrl("http://localhost:18902/swagger-ui.html")
.build();
}
}
- TestController
package com.yans.sb.manager.controller;
import com.yans.sb.manager.entity.TestEntity;
import com.yans.sb.manager.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@Api(description = "控制层")
@RestController
@RequestMapping("/manager/test")
public class TestController {
@Autowired
private TestService testService;
@ApiOperation("test方法")
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public TestEntity test(@PathVariable Integer id) {
System.out.println("id:" + id);
return testService.getById(id);
}
}
- TestDao
package com.yans.sb.manager.dao;
import com.yans.sb.manager.entity.TestEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface TestDao {
TestEntity getById(Integer id);
}
- TestEntity
package com.yans.sb.manager.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("TestEntity实体类")
public class TestEntity {
@ApiModelProperty("id 字段")
protected Integer id;
@ApiModelProperty("magicId 字段")
protected String magicId;
@ApiModelProperty("firstName 字段")
protected String firstName;
@ApiModelProperty("lastName 字段")
protected String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMagicId() {
return magicId;
}
public void setMagicId(String magicId) {
this.magicId = magicId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
- TestService
package com.yans.sb.manager.service;
import com.yans.sb.manager.dao.TestDao;
import com.yans.sb.manager.entity.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Autowired
private TestDao testDao ;
public TestEntity getById(Integer id){
return testDao.getById(id);
}
}
- TestDaoMapper.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="com.yans.sb.manager.dao.TestDao">
<!-- 根据主键查询-->
<select id="getById" resultType="com.yans.sb.manager.entity.TestEntity" parameterType="java.lang.Integer" >
select *
from test
where id = #{id}
</select>
</mapper>
- 创建表的sql
CREATE TABLE `test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`magic_id` varchar(32) NOT NULL,
`first_name` varchar(32) NOT NULL,
`last_name` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 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>
<!--使用jdbc的getGeneratedKeys获取数据库自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列标签替换列别名 默认未true-->
<setting name="useColumnLabel" value="true" />
<!--开启驼峰式命名转换:Table{create_time} -> Entity{createTime}-->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
- application.properties
#1.项目启动的端口
server.port=18902
#2.数据库连接参数
#2.1jdbc驱动,根据对应类厂家,这里mysql的驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
#2.2数据库连接url,包括ip(127.0.0.1)、端口(3306)、数据库名(testdb)
jdbc.url=jdbc:mysql://127.0.0.1:3306/cp?useUnicode=true&characterEncoding=utf-8&useSSL=false
#2.3数据库账号名
jdbc.username=root
#2.4数据库密码
jdbc.password=111111
#3.Mybatis配置
#3.1 mybatis配置文件所在路径
mybatis_config_file=mybatis-config.xml
#3.2 mapper文件所在路径,这样写可匹配mapper目录下的所有mapper,包括其子目录下的
mapper_path=/mapper/**/**.xml
#3.3 entity所在包
entity_package=com.yans.sb.manager.entity
测试
1、启动好数据库,创建目标数据库,创建表
14.png 15.png2、启动项目,点击这个三角形的图标
16.png
3、打开postman工具,配置如下,可以看到数据已经成功返回
postman.png
至此,项目工程搭建完毕,项目实例工程已经放到github,需要的自取,地址:https://github.com/andyccc/springbootdemo.git
网友评论