springboot框架
简介#
SpringBoot提供了⼀种快速使⽤Spring的⽅式,基于约定优于配置的思想,可以让
开发⼈员不必在配置与逻辑业务之间进⾏思维的切换,全身⼼的投⼊到逻辑业务的
代码编写中,从⽽⼤⼤提⾼了开发的效率,⼀定程度上缩短了项⽬周期。
SpringBoot项目创建#
方式一:maven方式#
1.创建⼀个普通的Maven⼯程
2.导⼊springBoot的依赖
<?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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--项目坐标-->
<groupId>com.qfedu.com</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<!--继承父类-父类定义了很多整合依赖的版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
</parent>
<!--对应的web框架-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3.编写⼀个主程序,启动Spring Boot应⽤
**
* @SpringBootApplication 来标注⼀个主程序类
*/
@SpringBootApplication
public class HelloWorldMainApplication {
public static void main(String[] args) {
// Spring应⽤启动起来
SpringApplication.run(HelloWorldMainApplication.class,args);
}
}
4.编写相关的Controller
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(String name){
return "hello world!!!";
}
}
5.启动程序,并完成浏览器访问测试
访问http://localhost:8080/hello
方式二:⽤Spring Initializr ⽅式构建#
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(String name){
return "hello world!!!";
}
}
SpringBoot 全局配置#
application.properties格式
server.port=80
application.yml格式
server:
port: 80
配置文件变量读取
yaml中保存的单个数据
使⽤@Value可以读取单个数据,属性名引⽤⽅式:${⼀级属性名.⼆级属性名……}
yaml获取全部数据
yaml对象数据封装⼀个Java对象
通过注解获取对应信息@ConfigurationProperties(prefix = "jdbc"),配合@Autowired获取该对象
springboot测试类#
1.测试类路径要和启动类一致/或手动指定启动类ContextConfiguration(classes = XXXApplication.class)
2.测试类加注解@SpringBootTest
@SpringBootTest
class JunitApplicationTests {
//注⼊你要测试的对象
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
//执⾏要测试的对象对应的⽅法
userDao.save();
System.out.println("user ... test...");
}
}
springboot+mybatis+chache#
1.实现数据库的增删查改
2.查询数据缓存到内置缓chache存中
3.日志配置,运行时日志存于文件
项目结构#
dao层#
mapper类和mapper.xml
package com.wning.springdemo.dao;
import com.wning.springdemo.entity.Customer;
import com.wning.springdemo.vo.CustomerVo;
import java.util.List;
public interface CustomerMapper {
//查询全部客户
List<Customer> queryAllCustomer(Customer customer);
//添加客户
void addCustomer(Customer customer);
//修改客户
void updateCustomer(Customer customer);
//根据identity删除用户
void deleteCustomer(String identity);
//根据identity查用户
Customer selectCustomerByIdentity(String identity);
}
package com.wning.springdemo.entity;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* customer实体类
*/
public class Customer {
private String identity;
private String custname;
private Integer sex;
private String address;
private String phone;
private String career;
@JsonFormat(pattern = "yyy-MM-dd HH:mm:ss" ,timezone = "GMT+8")
private Date createtime;
public void setIdentity(String identity) {
this.identity =identity == null?null:identity.trim();
}
public void setCustname(String custname) {
this.custname = custname == null?null:custname.trim();
}
public void setSex(Integer sex) {
this.sex = sex;
}
public void setAddress(String address) {
this.address = address == null?null:address.trim();
}
public void setPhone(String phone) {
this.phone = phone == null?null:phone.trim();
}
public void setCareer(String career) {
this.career = career;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getIdentity() {
return identity;
}
public String getCustname() {
return custname;
}
public Integer getSex() {
return sex;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
public String getCareer() {
return career;
}
public Date getCreatetime() {
return createtime;
}
public Customer() {
}
public Customer(String identity, String custname, Integer sex, String address, String phone, String career, Date createtime) {
this.identity = identity;
this.custname = custname;
this.sex = sex;
this.address = address;
this.phone = phone;
this.career = career;
this.createtime = createtime;
}
@Override
public String toString() {
return "{" +
" custname='" + custname + '\'' +
", sex=" + sex +
", address='" + address + '\'' +
", phone='" + phone + '\'' +
", career='" + career + '\'' +
", createtime=" + createtime +
", identity='" + identity + '\'' +
'}';
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wning.springdemo.dao.CustomerMapper">
<!-- 查询的字段,下方sql引用-->
<sql id ="Base_Column_List">
identity,custname,sex,address,phone,career,createtime
</sql>
<!--数据库中的字段映射实体类的字段-->
<resultMap id="BaseResultMap" type="com.wning.springdemo.entity.Customer">
<id column="identity" jdbcType="VARCHAR" property="identity"></id>
<result column="custname" jdbcType="VARCHAR" property="custname" ></result>
<result column="sex" jdbcType="INTEGER" property="sex" ></result>
<result column="address" jdbcType="VARCHAR" property="address" ></result>
<result column="phone" jdbcType="VARCHAR" property="phone" ></result>
<result column="career" jdbcType="VARCHAR" property="career" ></result>
<result column="createtime" jdbcType="TIMESTAMP" property="createtime" ></result>
</resultMap>
<!-- 多条件查询-->
<select id="queryAllCustomer" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/>
from t_customer
<where>
<if test="identity != null and identity != '' ">
and identity like concat("%",#{identity},"%")
</if>
<if test="custname != null and custname != '' ">
and custname like concat("%",#{custname},"%")
</if>
<if test="address != null and address != '' ">
and address like concat("%",#{address},"%")
</if>
<if test="phone != null and phone != '' ">
and phone like concat("%",#{phone},"%")
</if>
<if test="career != null and career != '' ">
and career like concat("%",#{career},"%")
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
order by createtime desc
</select>
<!-- 添加用户-->
<insert id="addCustomer" parameterType="com.wning.springdemo.vo.CustomerVo">
insert into t_customer
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="identity != null">
identity,
</if>
<if test="custname != null">
custname,
</if>
<if test="sex != null">
sex,
</if>
<if test="address != null">
address,
</if>
<if test="phone != null">
phone,
</if>
<if test="career != null">
career,
</if>
<if test="createtime != null">
createtime,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="identity != null">
#{identity},
</if>
<if test="custname != null">
#{custname},
</if>
<if test="sex != null">
#{sex},
</if>
<if test="address != null">
#{address},
</if>
<if test="phone != null">
#{phone},
</if>
<if test="career != null">
#{career},
</if>
<if test="createtime != null">
#{createtime},
</if>
</trim>
</insert>
<!-- 修改客户-->
<update id="updateCustomer">
update t_customer
<set>
<if test="custname != null">
custname=#{custname},
</if>
<if test="sex != null">
sex=#{sex},
</if>
<if test="address != null">
address=#{address},
</if>
<if test="phone != null">
phone=#{phone},
</if>
<if test="career != null">
career=#{career},
</if>
</set>
where identity = #{identity}
</update>
<!-- 删除-->
<delete id="deleteCustomer">
delete from t_customer where identity = #{identity}
</delete>
<!-- 根据身份证号查询-->
<select id="selectCustomerByIdentity" resultMap="BaseResultMap">
select * from t_customer where identity =#{identity}
</select>
</mapper>
service层#
package com.wning.springdemo.service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wning.springdemo.dao.CustomerMapper;
import com.wning.springdemo.entity.Customer;
import com.wning.springdemo.vo.CustomerVo;
import com.wning.springdemo.vo.DataGridView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerMapper customerMapper;
//分页查询
@Override
public DataGridView queryAllCustomer(CustomerVo customerVo) {
Page<Object> page = PageHelper.startPage(customerVo.getPage(),customerVo.getLimit());
List<Customer> customers = customerMapper.queryAllCustomer(customerVo);
return new DataGridView(page.getTotal(),customers);
}
//单用户查询
@Override
@Cacheable(value = "cacheHome",key = "#identity")
public Customer selectCustomerByIdentity(String identity) {
return customerMapper.selectCustomerByIdentity(identity);
}
//新增用户
@Override
public void addCustomer(CustomerVo customerVo) {
customerMapper.addCustomer(customerVo);
}
//修改用户
@Override
//删除缓存的key对应的内容
@CacheEvict(value = "cacheHome", key = "#customerVo.getIdentity()")
public void updateCostomer(CustomerVo customerVo) {
customerMapper.updateCustomer(customerVo);
}
//删除用户
@Override
//删除缓存的key对应的内容
@CacheEvict(value = "cacheHome", key = "#identity")
public void deleteCustomer(String identity) {
customerMapper.deleteCustomer(identity);
}
}
controller层#
package com.wning.springdemo.controller;
import com.wning.springdemo.entity.Customer;
import com.wning.springdemo.service.CustomerService;
import com.wning.springdemo.utils.ResultObj;
import com.wning.springdemo.vo.CustomerVo;
import com.wning.springdemo.vo.DataGridView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@Slf4j //系统日志使用
@RestController
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
//分页查询
@GetMapping
public DataGridView loadAllCustomer(@RequestBody CustomerVo customerVo){
// 录入对应的日志
log.debug("debug....");
log.info("info....");
log.warn("warn....");
log.error("error....");
return customerService.queryAllCustomer(customerVo);
}
@GetMapping("/one/{identity}")
public Customer selectCustomerByName(@PathVariable("identity") String identity){
log.warn("warn...."+identity);
return customerService.selectCustomerByIdentity(identity);
}
//添加用户
@PostMapping
public ResultObj addCustomer(@RequestBody CustomerVo customerVo){
try {
customerVo.setCreatetime(new Date());
customerService.addCustomer(customerVo);
return ResultObj.ADD_SUCCESS;
}catch (Exception e){
System.out.println(e);
return ResultObj.ADD_FAILS;
}
}
//修改客户
@PutMapping
public ResultObj updateCustomer(@RequestBody CustomerVo customerVo){
try {
customerService.updateCostomer(customerVo);
return ResultObj.UPDATE_SUCCESS;
}catch (Exception e){
System.out.println(e);
return ResultObj.UPDATE_FAILS;
}
}
//删除客户
@DeleteMapping
public ResultObj deleteCustomer(@RequestParam String identity){
try {
System.out.println(identity);
customerService.deleteCustomer(identity);
return ResultObj.DELETE_SUCCESS;
}catch (Exception e){
System.out.println(e);
return ResultObj.DELETE_FAILS;
}
}
}
配置实现#
server:
port: 80
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/testdb2?serverTimezone=UTC
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
main:
allow-circular-references: true
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
# 设置日志级别
logging:
# 日志分组
group:
myGroup: com.wning.springdemo.controller
# 日志级别
level:
root: info
myGroup: info
# 日志存储
file:
name: logs/server.log
logback:
rollingpolicy:
max-file-size: 1024KB
file-name-pattern: logs/server.%d{yyyy-MM-dd}.%i.log
项目pom#
<?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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wning</groupId>
<artifactId>springdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springdemo</name>
<description>springdemo</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!-- pagehelper分页工具-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- lombok,日志使用-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 内置缓存依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
补充-分页功能#
1.拿到分页对象PageHelper.startPage
2.获取全部数据
3.封装一个类,传入 page.getTotal 和 全部数据 自动实现分页功能
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」