使用Maven创建SpringBoot项目
1.创建Maven项目
2.选择项目类型
3.选择项目
4.编写项目组和名称-finish即可
5.修改pom.xml文件
<!-- spring boot基本环境 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
6.pom.xml中添加依赖
<!--web应用基本环境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
7.pom.xml中添加编译插件
<build>
<plugins>
<!-- spring-boot-maven-plugin插件就是打包spring boot应用的 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
8.编写启动类和控制器类
MySpring.java
@SpringBootApplication
public class MySpring
{
public static void main( String[] args )
{
SpringApplication.run(MySpring.class, args);
}
}
HelloController.java
@RestController
@RequestMapping("api/hello")
public class HelloController {
@PostMapping(value = "/create")
public String create(){
return "这是我的SpringBoot";
}
}
9.创建src/main/resources文件夹和application.yml文件
右键项目,new->Source Folder 输入src/main/resources
在创建好的src/main/resources上右键new->other->file 创建application.yml
在配置文件中配置端口,系统会默认识别
server:
port: 9101
在main方法上右键,run as -> java application 即可运行项目,在浏览器中输入 localhost:9101/api/hello/create即可获得数据
到此,最简单得springboot项目搭建完成
SpringBoot集成Swagger
swagger与Spring boot程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。
第一步:引入swagger的依赖文件:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
第二步:新建SwaggerConfig配置文件
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.myspring")).paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("GIS模块RESTful APIs")
.description("GIS服务提供")
.termsOfServiceUrl("https://www.baidu.com/")
.contact(new Contact("桃子味的白开水", "https://www.baidu.com/", ""))
.version("1.0")
.build();
}
}
第三步:Controller中加入swagger标识
@Api(value="测试接口",tags={"自己测试的接口"},hidden=false)
@RestController
@RequestMapping("api/hello")
public class HelloController {
@ApiOperation(value = "我的接口", notes = "仅作测试")
@PostMapping(value = "/create")
public String create(){
return "这是我的SpringBoot";
}
}
SpringBoot 热部署
在Spring Boot实现代码热部署是一件很简单的事情,代码的修改可以自动部署并重新热启动项目。
<!--spring-boot 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
SpringBoot 使用mybatis连接mysql数据库。
1.配置依赖
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
<!-- MySql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.配置application.yml文件
spring:
application:
name: gis
datasource:
# 数据源基本配置
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:Mapper/*Mapper.xml
#这里是与Mapper.xml对应的包
type-aliases-package: com.springboot.myspring.dao
3.编写功能类
userMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springboot.myspring.dao.UserMapper">
<select id="getUser" resultType="com.springboot.myspring.dto.User">
select * from user
</select>
<delete id="deleteUser" parameterType="Integer">
delete from user where id =#{id}
</delete>
<insert id="addUser" parameterType="com.springboot.myspring.dto.User">
insert into user(id,name,age,sex)values(#{id},#{name},#{age},#{sex})
</insert>
</mapper>
User.java
package com.springboot.myspring.dto;
import org.springframework.stereotype.Component;
@Component
public class User {
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 String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
private int id;
private String name;
private String age;
private String sex;
}
UserMapper.java
package com.springboot.myspring.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.myspring.dto.User;
@Mapper
public interface UserMapper {
public List<User> getUser() throws Exception;
public void deleteUser(int id) throws Exception;
public void addUser(User user) throws Exception;
}
UserService.java
package com.springboot.myspring.service;
import java.util.List;
import com.springboot.myspring.dto.User;
public interface UserService {
public List<User> getUser() throws Exception;
public void deleteUser(int id) throws Exception;
public void addUser(User user) throws Exception;
}
UserServiceImpl.java
package com.springboot.myspring.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.myspring.dao.UserMapper;
import com.springboot.myspring.dto.User;
import com.springboot.myspring.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getUser() throws Exception {
return userMapper.getUser();
}
@Override
public void deleteUser(int id) throws Exception {
userMapper.deleteUser(id);
}
@Override
public void addUser(User user) throws Exception {
userMapper.addUser(user);
}
}
UserController.java
package com.springboot.myspring.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.myspring.dto.User;
import com.springboot.myspring.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value="用户接口")
@RestController
@RequestMapping("api/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private User user;
@ApiOperation(value="获取用户",notes="获取用户")
@PostMapping("getUser")
public List<User> getUser() throws Exception{
return userService.getUser();
}
@PostMapping("delect")
public String deleteUser(@RequestParam("id") int id) throws Exception{
userService.deleteUser(id);
return "你已经删掉了id为"+id+"的用户";
}
@PostMapping("addUser")
public String addUser() throws Exception{
user.setAge("18");
user.setName("小明");
userService.addUser(user);
return "增加用户";
}
}
至此,springboot已经可以通过mybatis连接mysql数据库并实现增上改查功能了,切记,要在mysql中创建好相应的表和字段。
SpringBoot使用Druid进行数据库监控
对于数据访问层,无论是Sql还是NoSql,SpringBoot默认采用整合SpringData的方式进行统一管理,添加大量的自动配置,屏蔽了很多设置。引入了各种XxxTemplate和XxxRepository来简化我们对数据访问层的操作。
SpringBoot2.0默认是用com.zaxxer.hikari.HikariDataSource作为数据源。
2.0以下默认采用的是org.apache.tomcat.jdbc.pool.DataSource作为数据源。
Hikari的官方网站:http://brettwooldridge.github.io/HikariCP/
Hikari号称JAVA领域中最快的数据连接池,不过再快我也觉得没有阿里巴巴奉献给apache的Druid好,因为阿里巴巴的服务周到,里面有监控中心,可以帮助我们快速定位慢sql等。
Apache Druid(Incubating) - 面向列的分布式数据存储,非常适合为交互式应用程序提供动力
虽然HikariDataSource性能非常高,但是阿里的druid数据源配有成套的数据源管理软件,开发中使用的更多。
1.添加依赖
以往我们都是直接引入Druid的依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
但是面对火爆的SpringBoot,apache出了一套完美支持SpringBoot的方案所以说我们不使用上面的依赖而是使用:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2.配置application.yml文件,对比配置mysql数据源的配置
spring:
application:
name: gis
datasource:
# 数据源基本配置
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.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
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
mapper-locations: classpath:Mapper/*Mapper.xml
#这里是与Mapper.xml对应的包
type-aliases-package: com.springboot.myspring.dao
3.手动创建DruidConfiguration.java文件
虽然我们配置了druid连接池的其它属性,但是不会生效。因为默认是使用的java.sql.Datasource的类来获取属性的,有些属性datasource没有。如果我们想让配置生效,需要手动创建Druid的配置文件。
Druid的最强大之处在于它有着强大的监控,可以监控我们发送到数据库的所有sql语句。方便我们后期排插错误。
package com.springboot.myspring.configure;
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 com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@Configuration
public class DruidConfiguration {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource druidDataSource(){
return new DruidDataSource();
}
/**
* 配置监控服务器
* @return 返回监控注册的servlet对象
* @author SimpleWu
*/
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 添加IP白名单
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
// 添加控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "root");
servletRegistrationBean.addInitParameter("loginPassword", "123456");
// 是否能够重置数据
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* 配置服务过滤器
*
* @return 返回过滤器配置对象
*/
@Bean
public FilterRegistrationBean statFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则
filterRegistrationBean.addUrlPatterns("/*");
// 忽略过滤格式
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
return filterRegistrationBean;
}
}
配置完后我们启动SpringBoot程序访问:
http://localhost:8080/druid/ 就可以来到我们的登录页面面就是我们上面添加的控制台管理用户,我们可以在上面很好的看到运行状况,