序、说明
也没什么好说明的
一、项目创建
1.png
2.png
二、添加常用依赖
- fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
- mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
- mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
以上三个依赖基本每个项目都会用到,数据库根据情况选择不同的驱动即可。
三、创建项目文件夹结构
- Config
- Controller
- Mapper
- Model
- Service
- ServiceImpl
- Utils
3.png
四、配置文件初始化
#设置springboot启动端口
server.port=9090
spring.datasource.url=jdbc:mysql://localhost:3306/java_example?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
五、基本必改代码
1、SpringbootApplication扫描Mapper文件夹
@MapperScan("com.javaexample.springboot.Mapper")
package com.javaexample.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.javaexample.springboot.Mapper")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
2、设置跨域
在Config文件夹内新建个CorsConfig类
package com.javaexample.springboot.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
3、常用Utils类
1)响应工具类:ResponseManager
先创建需要用到的Pojo:ResponsePojo
package com.javaexample.springboot.Model;
import java.util.List;
public class ResponsePojo<T> {
private int code;
private String msg;
private T data;
private List list;
public ResponsePojo(int code, String msg) {
this.code = code;
this.msg = msg;
}
public ResponsePojo(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public ResponsePojo(int code, String msg, List list) {
this.code = code;
this.msg = msg;
this.list = list;
}
public ResponsePojo(int code, String msg, T data, List list) {
this.code = code;
this.msg = msg;
this.data = data;
this.list = list;
}
// getter & setter & toString
}
然后创建ResponseManager
package com.javaexample.springboot.Utils;
import com.javaexample.springboot.Model.ResponsePojo;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ResponseManager {
private static final int OK = 200;
private static final int ERROR = 400;
public static ResponsePojo buildSuccess() {
return new ResponsePojo(OK,"请求成功");
}
public static ResponsePojo buildSuccess(String msg) {
return new ResponsePojo(OK,msg);
}
public static <T> ResponsePojo buildSuccess(T data) {
return new ResponsePojo(OK,"请求成功", data);
}
public static ResponsePojo buildSuccess(List list) {
return new ResponsePojo(OK,"请求成功", list);
}
public static <T> ResponsePojo buildSuccess(T data, List list) {
return new ResponsePojo(OK,"请求成功", data,list);
}
public static ResponsePojo buildError() {
return new ResponsePojo(ERROR,"请求失败");
}
public static ResponsePojo buildError(String msg) {
return new ResponsePojo(ERROR,msg);
}
public static ResponsePojo buildError(int code,String msg) {
return new ResponsePojo(code,msg);
}
public static <T> ResponsePojo buildError(int code,String msg,T data) {
return new ResponsePojo(code,msg,data);
}
}
使用时就这样
@Autowired
private ResponseManager responseManager;
...
public ResponsePojo xxxx(){
...
return responseManager.buildSuccess();
}
2)强制获取Spring中的组件:SpringManager
当无法通过@Autowired注入时就这样强制获取(个人是这样理解)
package com.javaexample.springboot.Utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringManager implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringManager.applicationContext == null){
SpringManager.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
使用时就这样
private ApplicationContext applicationContext = SpringManager.getApplicationContext();
private AsyncTaskService asyncTaskService = applicationContext.getBean(AsyncTaskService.class);
六、业务代码Example
1、准备工作
此示例基于Mysql数据库,先新建数据库java_example,再初始化表ex_user。
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50635
Source Host : localhost:3306
Source Database : java_example
Target Server Type : MYSQL
Target Server Version : 50635
File Encoding : 65001
Date: 2019-11-18 17:14:10
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for ex_user
-- ----------------------------
DROP TABLE IF EXISTS `ex_user`;
CREATE TABLE `ex_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`login_at` datetime DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
反正比较简单,就随便建了几个字段,将实现get、post等基本操作。
2、创建实体类UserEntity
package com.javaexample.springboot.Model;
public class UserEntity {
private int userId;
private String userName;
private String password;
private String loginAt;
//getter & setter & toString
}
3、创建控制器UserController
在Controller文件夹中创建UserController
package com.javaexample.springboot.Controller;
import com.javaexample.springboot.Model.ResponsePojo;
import com.javaexample.springboot.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
@ResponseBody
public ResponsePojo userLogin(@RequestBody Map<String, String> data) {
ResponsePojo responsePojo = userService.userLogin(data.get("userName"), data.get("password"));
return responsePojo;
}
@GetMapping("/info")
@ResponseBody
public ResponsePojo getUserInfo(@RequestParam("userId") int userId) {
ResponsePojo responsePojo = userService.getUserInfo(userId);
return responsePojo;
}
}
4、创建业务层接口:UserService
package com.javaexample.springboot.Service;
import com.javaexample.springboot.Model.ResponsePojo;
public interface UserService {
ResponsePojo userLogin(String userName,String password);
ResponsePojo getUserInfo(int userId);
}
5、创建业务层接口实现:UserServiceImpl
package com.javaexample.springboot.ServiceImpl;
import com.javaexample.springboot.Mapper.UserMapper;
import com.javaexample.springboot.Model.ResponsePojo;
import com.javaexample.springboot.Model.UserEntity;
import com.javaexample.springboot.Service.UserService;
import com.javaexample.springboot.Utils.ResponseManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private ResponseManager responseManager;
public ResponsePojo userLogin(String userName,String password){
UserEntity user = userMapper.userLogin(userName, password);
if (user == null) {
return responseManager.buildError(11002, "密码错误");
}
userMapper.updateLoginInfo(user);
return responseManager.buildSuccess();
}
public ResponsePojo getUserInfo(int userId) {
UserEntity user = userMapper.getUserInfo(userId);
return responseManager.buildSuccess(user);
}
}
6、创建持久层:UserMapper
package com.javaexample.springboot.Mapper;
import com.javaexample.springboot.Model.UserEntity;
import org.apache.ibatis.annotations.*;
public interface UserMapper {
@Select("SELECT user_id, user_name FROM ex_user where user_name = #{userName} and password = #{password}")
@Results({
@Result(property = "userId", column = "user_id"),
@Result(property = "userName", column = "user_name")
})
UserEntity userLogin(@Param("userName") String userName, @Param("password") String password);
@Update("UPDATE ex_user SET login_at = now() WHERE user_id =#{user_id}")
void updateLoginInfo(UserEntity user);
@Select("SELECT user_id,user_name,password,login_at FROM ex_user where user_id = #{userId}")
@Results({
@Result(property = "userId", column = "user_id", javaType = Integer.class),
@Result(property = "userName", column = "user_name", javaType = String.class),
@Result(property = "password", column = "password", javaType = String.class),
@Result(property = "loginAt", column = "login_at", javaType = String.class)
})
UserEntity getUserInfo(@Param("userId") int userId);
}
7、说明
2、3、4、5、6这几步都是一气呵成,先一股脑创建完,然后挨个引用就行。其中实体类根据数据库结构来生成。
至此,项目demo初步完成,接下来试运行看看效果。
七、运行效果及项目结构图
在IDEA中运行,并通过浏览器或postman调用接口
(POST)http://localhost:9090/user/login
(GET)http://localhost:9090/user/info
注:端口默认是8080,或者根据application.properties中设置的server.port来
TIM图片20191119101523.png
TIM图片20191119101710.png
TIM图片20191119103119.png
八、打包发布
打包直接用IDEA自带的maven打包工具打包,或先切换到项目根目录,再执行下面语句。
mvn clean package -Dmaven.test.skip=true
打包后的jar文件,通过下面语句执行。(springboot.jar是我打包后的名字)
java -jar springboot.jar
九、完成
到这里第一个springboot&mybatis&mysql的示例项目已完成。