SpringBoot学习day1-SpringBoot的简介与搭建

  • springboot
    • 回顾spring
    • springboot
    • springboot搭建(新闻为例)
    • springboot中的配置文件
    • spring集成jdbc,mybatis,阿里巴巴数据源
    • **SpringBoot 集成日志功能**(了解)
      • 常用日志组件
      • 日志级别
    • springboot统一异常处理

springboot

回顾spring

spring是一个轻量级的IOC和AOP的一站式框架,为简化企业级应用开发而生.

优点:

​ 轻量级

​ IOC

​ AOP

解耦 (代码之间的耦合度降低了, 例如IOC,由框架创建管理对象, AOP可以将业务代码和非业务代码分离)

一站式 (数据访问层 数据连接对象管理,mybatis,事务), 对web层的Servlet进行封装

开源

很方便的集成其他的框架

缺点:

1.配置是重量级的,而且大量是模板化配置

    <!--属于很啰嗦的模板化配置--><!--开启aop自动代理--><aop:aspectj-autoproxy></aop:aspectj-autoproxy><!-- 开启注解事务管理 --><tx:annotation-driven transaction-manager="transactionManager"/><!--开启web层的注解--><mvc:annotation-driven></mvc:annotation-driven>

2.项目中需要导入很多相关的依赖坐标(例如 json组件, 跨域过滤器…)

springboot

springboot是在spring的基础上,对spring应用的搭建进行简化,基于约定大于配置的思想(大家公认的做法,那么框架也就默认把一些功能直接实现了,例如我们现在都用注解开发),可以创建一个企业级应用程序, 内嵌服务器(tomcat),有量大核心功能: 起步依赖: 当我们使用spring基本的依赖时, 自动就会将相关的依赖导入进来。自动配置: spring启动时,可以根据我们项目中配置的相关依赖,自动加载配置.

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

Wetake an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration

springboot搭建(新闻为例)

1.创建一个普通的maven项目

image-20250610140249670

2.配置 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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>SpringBoot</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><!--指定 jdk 版本--><java.version>1.8</java.version></properties><!--依赖的父级工程--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.6</version><relativePath/></parent><!--添加基本的 springweb 依赖--><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><!--打包插件--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.6.6</version></plugin></plugins></build></project>  

创建启动类NewsApplication

image-20250610170144738

package org.example;import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
@SpringBootApplicationpublic class NewsApplication {public static void main(String[] args) {SpringApplication.run(NewsApplication.class);}
}

3.创建自定义的处理器(web包)

@RestController
@RequestMapping(path = "/loginCtl")
public class LoginController {@RequestMapping(path = "/login")public String login(){System.out.println("aaaaaaaaaaaaa");return "success";}
}

启动mian

image-20250610170401963

启动成功!!!

tips:可以在Ascii艺术字实现个性化Spring Boot启动banner图案,轻松修改更换banner.txt文件内容,收集了丰富的banner艺术字和图,并且支持中文banner下载,让你的banner好玩儿更有意思。-bootschool.net网站下载启动时候的图案

image-20250610171938430

4.访问

​ ip:端口/处理地址/方法地址

springboot中的配置文件

springboot中的配置文件,严格意义上不是配置文件, 是用来存储配置参数的文件(里面放的是参数值).

配置文件有两种格式:

  1. 属性文件 .properties

    image-20250610170846629

    键 = 值
    server.port=8089
    spring.datasource.driver-class-name=
    spring.datasource.url=
    spring.activemq.password=
    spring.datasource.username=
    

2.yml

#配置服务器端口
server:port: 8088spring:datasource:driver-class-name:url:username:password:

spring集成jdbc,mybatis,阿里巴巴数据源

1.导入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency><!--mysql-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version>
</dependency><!-- 阿里巴巴数据源 -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version>
</dependency>

2.application.yml配置文件(在resource文件夹内)

# 端口号
server:port: 8080
# 数据库配置
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/spring_demo?serverTimezone=Asia/Shanghaiusername: rootpassword: root# 使用阿里巴巴的druid连接池type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 5max-active: 20max-wait: 60000
# mybatis配置
mybatis:# 扫描mapper包type-aliases-package: org.example.model# mapper.xml文件位置mapper-locations: classpath:mapper/*Mapper.xml# 加载全局配置文件configuration:# 驼峰命名map-underscore-to-camel-case: true# 自动加载mapper.xmlcache-enabled: true# 打印sql语句log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

对启动类进行配置@MapperScan("org.example.dao") // This line is used to scan the DAO package for SQL mappers

package org.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;// This is the main class of the News Application
@SpringBootApplication
@MapperScan("org.example.dao") // This line is used to scan the DAO package for SQL mapperspublic class NewsApplication {public static void main(String[] args) {SpringApplication.run(NewsApplication.class);}
}

3.创建服务类

package org.example.service;import org.example.dao.LoginDao;
import org.example.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;@Service
// 这个注解表示这是一个服务类,并且在事务中进行操作,如果出现异常,则回滚事务
@Transactional(rollbackFor = Exception.class)
public class LoginService {@AutowiredLoginDao loginDao;public Admin login(Admin admin) {return loginDao.login(admin);}
}

编写LoginController类

package org.example.web;import org.example.model.Admin;
import org.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/loginCtl")
public class LoginController {@AutowiredLoginService loginService;@RequestMapping(path = "/login")public Admin login(@RequestBody Admin admin){Admin admin1 = loginService.login(admin);System.out.println("aaaaaaaaaaaaa");return admin1;}}

使用ApiPost测试

image-20250610181215092

image-20250610181314015

成功!!

最终文件结构

image-20250610181349786

SpringBoot 集成日志功能(了解)

日志?

日志是程序中重要组成部分,可以监测程序运行轨迹, 记录参数值的变化.尤其是生产环境中非常必要, 通过日志文件可以快速的定位到问题.

什么时候使用日志

答:实际生产环境

常用日志组件

  • slf4j(Simple Logging Facade for Java)
  • commons-logging
  • Log4J
  • Log4J2
  • Logback
  • JUL(Java Utils Logging)

日志级别

从低到高:debug<info<warn<error

logging:level:org.example: infofile:name: D:/log/log.log#类里面配置Logger对象   private static Logger logger = LoggerFactory.getLogger(LoginController.class);logger.debug("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.info("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.warn("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.error("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());

保存位置如下

image-20250611170438969

在LoginController添加Logger对象

package org.example.web;import org.example.model.Admin;
import org.example.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/loginCtl")
public class LoginController {private static Logger logger = LoggerFactory.getLogger(LoginController.class);@AutowiredLoginService loginService;@RequestMapping(path = "/login")public Admin login(@RequestBody Admin admin) {logger.debug("input account:{},paasord:{}", admin.getAccount(), admin.getPassword());logger.info("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());logger.warn("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());logger.error("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());/*@RequestBody 作用是将请求体中的json数据绑定到Admin对象中*/Admin admin1 = loginService.login(admin);System.out.println("aaaaaaaaaaaaa");return admin1;}}

项目中统一异常打印

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package org.example.util;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;@Component
@Aspect
public class LogAspect {private static Logger logger = LoggerFactory.getLogger(LogAspect.class);@Before("execution(public * org.example.web.*.*(..))")public void savelog(JoinPoint joinPoint) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();// 记录下请求内容logger.info("HTTP_METHOD :{} ", request.getMethod());logger.info("IP : {}", request.getRemoteAddr());//客户端 ipObject[] objs = joinPoint.getArgs(); //获取方法参数logger.info(Arrays.toString(objs));}
}

image-20250611170400681

springboot统一异常处理

/*全局统一的异常处理类*/
@RestControllerAdvice
public class GlobalExceptionHandler {private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);/*** 异常处理*/@ExceptionHandler(Exception.class)public Result globalException(Exception e) {Result commonResult = new Result(500,"系统忙:"+e.getMessage(),null);logger.info("Exception : "+e.getMessage());//向日志文件打印信息return commonResult;//向前端用户响应信息}
}

统一日志打印,统一异常处理都是AOP的实际使用场景, spring中的事务管理也是AOP的使用场景

到此,后端最基本的功能搭建完成.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/diannao/86657.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【牛客小白月赛117】E题——种类数小结

1 初步想法 1.1 前置知识&#xff1a;vector数组的去重操作 unique()将不重复的元素放在数组前面&#xff0c;重复元素移到后面&#xff0c;qs获取不重复元素的后一个位置&#xff0c;之后用erase()函数去除重复元素。 qsunique(a.begin()1,a.begin()k1); a.erase(qs,a.end(…

linux之kylin系统nginx的安装

一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源&#xff08;HTML/CSS/图片等&#xff09;&#xff0c;响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址&#xff0c;提高安全性 3.负载均衡服务器 支持多种策略分发流量…

MatAnyone本地部署,视频分割处理,绿幕抠像(WIN/MAC)

大家好&#xff0c;今天要和大家分享的项目是MatAnyone&#xff0c;与上一篇分享的SAM2LONG类似&#xff0c;不过上次的分享没有提到如何在 MAC 上部署&#xff0c;后来有小伙伴私信说希望能出一个 MAC 版本的。那正好看到MatAnyone这个项目顺手就写下来。该项目基于SAM2同样可…

记录下blog的成长过程

2025-06-11 新人榜83 2025-06-09 新人榜87 北京市原力月榜 80

C语言学习20250611

指针 指针类型 int p;》普通的整形变量int *p;》p先与*结合&#xff0c;表示p为指针&#xff0c;该指针指向的内容的数据类型为整型int p[3];》p为一个由整型数据组成的数组int *p[3];》因为[]比*优先级高&#xff0c;p先与方括号结合&#xff0c;所以p为一个数组&#xff0c…

【AI智能体】Dify 从部署到使用操作详解

目录 一、前言 二、Dify 介绍 2.1 Dify 是什么 2.2 Dify 核心特性 2.2.1 多模型支持 2.2.2 可视化编排工作流 2.2.3 低代码/无代码开发 2.3 Dify 适用场景 2.4 Dify 与Coze的对比 2.4.1 定位与目标用户 2.4.2 核心功能对比 2.4.3 开发体验与成本 2.4.4 适用场景对比…

Java爬虫库的选择与实战代码

如果你的项目正在Java中考虑引入爬虫能力&#xff0c;无论是做数据分析、信息聚合&#xff0c;还是竞品监测&#xff0c;选对库确实能大幅提升开发效率和运行效果。结合当前主流库的特点与适用场景&#xff0c;我整理了一份更贴近实战的对比分析&#xff0c;并附上可直接运行的…

详细解释aruco::markdetection _detectInitialCandidates函数

_detectInitialCandidates 是 OpenCV 的 ArUco 模块中一个非常关键的函数&#xff0c;它负责检测图像中的候选 ArUco 标记。该函数的主要目标是&#xff1a; 使用多个尺度&#xff08;scale&#xff09;对输入图像进行自适应阈值处理&#xff1b;在每个尺度下提取轮廓并筛选出…

Android 开发中配置 USB 配件模式(Accessory Mode) 配件过滤器的配置

在 Android 开发中配置 USB 配件模式&#xff08;Accessory Mode&#xff09; 的配件过滤器&#xff08;accessory_filter.xml&#xff09;&#xff0c;需要以下步骤&#xff1a; 1. 创建配件过滤器文件 在项目的 res/xml/ 目录下创建 accessory_filter.xml 文件&#xff08;若…

FreeRTOS互斥量

目录 1.使用场合2.函数2.1 创建2.1.1 动态创建2.1.2 静态创建 2.2 删除2.3 释放&#xff08;Give&#xff09;2.4 获取&#xff08;Take&#xff09;2.5 ISR 版本注意事项 3.常规使用流程4.和二进制信号量的对比5.递归锁5.1 死锁5.2 概念5.2.1 问题5.2.2 解决方案&#xff1a;递…

ThinkPad 交换 Ctrl 键和 Fn 键

概述 不知道那个大聪明设计的将fn设置在最左边&#xff0c;xxx&#xff0c;我服了&#xff0c;你这个老六真恶心。 方法 一&#xff1a;BIOS/UEFI 设置&#xff08;推荐&#xff09; 重启 你的 ThinkPad。 在启动时按下 F1&#xff08;或 Enter&#xff0c;再按 F1&#xff0…

`dispatch_source_t` 计时器 vs `NSTimer`:核心差异一览

维度GCD 计时器 (dispatch_source_t)NSTimer依赖机制直接挂在 GCD 队列;底层走 Mach 内核定时源挂在 RunLoop,必须指定 RunLoop & mode线程上下文哪个队列就在哪条线程回调(例中用 dispatch_get_main_queue())总在定时器所在的 RunLoop 线程(默认主线程 & NSDefau…

ubuntu22.04系统安装部署docker和docker compose全过程!

更新系统包 首先&#xff0c;确保系统包是最新的&#xff1a; sudo apt updatesudo apt upgrade -y安装依赖 安装 Docker 所需的依赖包&#xff1a; sudo apt install -y apt-transport-https ca-certificates curl software-properties-common添加 Docker 官方 GPG 密钥 添加…

企业如何增强终端安全?

在数字化转型加速的今天&#xff0c;企业的业务运行越来越依赖于终端设备。从员工的笔记本电脑、智能手机&#xff0c;到工厂里的物联网设备、智能传感器&#xff0c;这些终端构成了企业与外部世界连接的 “神经末梢”。然而&#xff0c;随着远程办公的常态化和设备接入的爆炸式…

VS2017----打开ui文件几秒后闪退

问题描述 在vs2017中双击ui文件能够打开,但是几秒后就闪退了,提示报错 问题解决 QT VS tools ----Options,把这个设置为True保存即可

深入解析Docker网桥模式:从docker0到容器网络的完整通信链路

1. 简介docker 网桥模式 Docker 启动时默认创建 docker0 虚拟网桥&#xff08;Linux bridge&#xff09;&#xff0c;并分配私有 IP 地址范围&#xff08;如 172.17.42.1/16&#xff09;&#xff0c;它的作用相当于一个虚拟交换机&#xff0c;让宿主机和多个容器之间可以通信。…

Proof of Talk专访CertiK联创顾荣辉:全周期安全方案护航Web3生态

6月10日&#xff0c;CertiK联合创始人兼CEO顾荣辉在Proof of Talk 2025举办期间&#xff0c;接受大会官方专访&#xff0c;分享了他对Web3安全现状的观察以及CertiK的安全战略布局。 顾荣辉指出&#xff0c;虽然安全的重要性被广泛认可&#xff0c;但许多创业者和开发者仍存在…

再说一说LangChain Runnable接口

之前我们介绍过LangChain通过Runnable和LCEL来实现各个组件的快捷拼装&#xff0c;整个过程就像拼积木一样。 今天我们深入剖析Runnable接口的底层实现逻辑。 往期文章推荐: 16.Docker实战&#xff1a;5分钟搞定MySQL容器化部署与最佳实践15.Ollama模板全解析&#xff1a;从基…

LLaMA-Factory微调Qwen3模型完了,怎么直接用vllm推理模型?

环境&#xff1a; LLaMA-Factory vllm0.8.5 Qwen3-8b 问题描述&#xff1a; LLaMA-Factory微调Qwen3模型完了,怎么直接用vllm推理模型&#xff1f; 解决方案&#xff1a; 一、合并 LoRA 权重与基础模型 vLLM 需要完整的模型文件&#xff08;含合并后的权重&#xff09;…

C#AES加密

一、AES 加密概念 定义 &#xff1a;AES&#xff08;Advanced Encryption Standard&#xff0c;高级加密标准&#xff09;是一种对称加密算法&#xff0c;由美国国家标准与技术研究院&#xff08;NIST&#xff09;于 2001 年发布&#xff0c;用于替代之前的 DES&#xff08;数据…