当前位置: 首页 > news >正文

Springboot 实战运用

一,基本配置

1,pom文件配置介绍

1.1继承
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.2</version><relativePath/> <!-- lookup parent from repository -->
</parent>

Spring Boot 的父级依赖,只有继承它项目才是 Spring Boot 项目。

spring-boot-starter-parent 是一个特殊的 starter,它用来提供相关的 Maven 默认依赖。使

用它之后,常用的包依赖可以省去 version 标签

1.2依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

web项目的启动依赖

1.3插件
<plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin>

spring-boot-maven-plugin 插件是将 springboot 的应用程序打包成 jar 包的插件。将所有

应用启动运行所需要的 jar 包都包含进来,从逻辑上将具备了独立运行的条件。当运行"mvn

package"进行打包后,使用"java -jar"命令就可以直接运行。

2.启动类与启动器

启动类与启动器的区别: 启动类表示项目的启动入口

启动器表示 jar 包的坐标

2.1启动类

Spring Boot 的启动类的作用是启动 Spring Boot 项目,是基于 Main 方法来运行的。

注意:启动类在启动时会做注解扫描(@Controller、@Service、@Repository......),扫描

位置为同包或者子包下的注解,所以启动类的位置应放于包的根下。

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
@MapperScan("com.rojer.springboot.mapper")
@SpringBootApplication
public class SpringbootApplication {
​public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
​
}
2.2启动器

Spring Boot 将所有的功能场景都抽取出来,做成一个个的 starter(启动器),只需要在项

目里面引入这些 starter 相关场景的所有依赖都会导入进来,要用什么功能就导入什么场景,

在 jar 包管理上非常方便,最终实现一站式开发。

如:

spring-boot-starter

这是 Spring Boot 的核心启动器,包含了自动配置、日志和 YAML。

spring-boot-starter-actuator

帮助监控和管理应用。

spring-boot-starter-web

支持全栈式 Web 开发,包括 Tomcat 和 spring-webmvc。

spring-boot-starter-amqp

通过 spring-rabbit 来支持 AMQP 协议(Advanced Message Queuing Protocol)。

spring-boot-starter-aop

支持面向切面的编程即 AOP,包括 spring-aop 和 AspectJ。

3.yml文件的配置

3.1格式要求
  • 大小写敏感

  • 使用缩进来代表层级关系

  • 相同部分只出现一次

3.2yml文件存放位置
  • 当前项目根目录中

  • 当前项目根目录下的一个/config 子目录中

  • 项目的 resources 即 classpath 根路径中

  • 项目的 resources 即 classpath 根路径下的/config 目录中

3.3 yml实际配置
#配置端口
server:port: 8080
​
spring:servlet:multipart:#配置单个上传文件大小的限制max-file-size: 3MB#配置在一次请求中上传文件的总容量max-request-size: 10MB#配置数据源datasource:url: jdbc:mysql://localhost:3306/product?useSSL=true&serverTimezone=GMT%2B8username: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver#mybatis的额外配置
mybatis:configuration:map-underscore-to-camel-case: truetype-aliases-package: com.sxt.sringboot.entitymapper-locations: classpath:mapper/*.xml

4.bootstrap文件配置

4.1bootstrap介绍和特征

Spring Boot 中有两种上下文对象,一种是 bootstrap, 另外一种是 application, bootstrap 是应用程序的父上下文,也就是说 bootstrap 加载优先于 applicaton。bootstrap 主要用于从 额外的资源来加载配置信息,还可以在本地外部配置文件中解密属性。这两个上下文共用一 个环境,它是任何 Spring 应用程序的外部属性的来源。bootstrap 里面的属性会优先加载, 它们默认也不能被本地相同配置覆盖。

  • boostrap 由父 ApplicationContext 加载,比 applicaton 优先加载。

  • boostrap 里面的属性不能被覆盖。

5.spring boot核心注解介绍

5.1@SpringBootApplication

是 SpringBoot 的启动类。

此注解等同于@Configuration+@EnableAutoConfiguration+@ComponentScan 的组合。

5.2@SpringBootConfiguration

@SpringBootConfiguration 注解是@Configuration 注解的派生注解,跟@Configuration

注解的功能一致,标注这个类是一个配置类,只不过@SpringBootConfiguration 是 springboot

的注解,而@Configuration 是 spring 的注解

5.3@Configuration

通过对 bean 对象的操作替代 spring 中 xml 文件

5.4@EnableAutoConfiguration

Spring Boot 自动配置(auto-configuration):尝试根据你添加的 jar 依赖自动配置你的

Spring 应用。是@AutoConfigurationPackage 和@Import(AutoConfigurationImportSelector.class)

注解的组合。

5.5@AutoConfigurationPackage

@AutoConfigurationPackage 注解,自动注入主类下所在包下所有的加了注解的类

(@Controller,@Service 等),以及配置类(@Configuration)

5.6@Import({AutoConfigurationImportSelector.class})

直接导入普通的类

导入实现了 ImportSelector 接口的类

导入实现了 ImportBeanDefinitionRegistrar 接口的类

5.7@ComponentScan

组件扫描,可自动发现和装配一些 Bean。

5.8@ConfigurationPropertiesScan

@ConfigurationPropertiesScan 扫描配置属性。@EnableConfigurationProperties 注解的作

用是使用 @ConfigurationProperties 注解的类生效。

二,基本业务的实现

1,修改pom文件加入相关依赖

<dependencies><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.11</version></dependency>
<!--        数据库坐标驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency>
<!--        Druid数据源依赖--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--        导入mybatis包--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency></dependencies>

2,编辑yml文件,建立基本配置,如配置端口,数据源等

#配置端口
server:port: 8080
​
spring:servlet:multipart:#配置单个上传文件大小的限制max-file-size: 3MB#配置在一次请求中上传文件的总容量max-request-size: 10MB#配置数据源datasource:url: jdbc:mysql://localhost:3306/product?useSSL=true&serverTimezone=GMT%2B8username: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver#mybatis的额外配置
mybatis:configuration:map-underscore-to-camel-case: truetype-aliases-package: com.sxt.sringboot.entitymapper-locations: classpath:mapper/*.xml

3,修改启动类,使其扫描mapper包

@MapperScan("com.rojer.springboot.mapper")
@SpringBootApplication
public class SpringbootApplication {
​public static void main(String[] args) {SpringApplication.run(SpringbootApplication.class, args);}
​
}

4,建立controller层,mapper接口,service接口,service实现类

controller层

/***公司controller层*/
@RestController
@RequestMapping("/back/Company")
public class CompanyController {@Autowiredprivate CompanyService companyService;@PostMapping("/CompanyUpdate")public CommonResult companyUpdate(Company company){companyService.update(company);return CommonResult.success();}@PostMapping("/CompanyFindAll")public CommonResult companyFindAll(Company company){List<Company> all = companyService.findAll(company);return CommonResult.success(all);}
}

mapper接口

/*** 公司mapper接口*/
public interface CompanyDao extends BaseDao<Company> {
//    使用注释方法@Override@Update("UPDATE `company_information` SET `name` = #{name}, `englishName` = #{englishName},`phone` = #{phone}, `mail` = #{mail}, `fax` = #{fax}, `address` = #{address}, `logo` = #{logo} WHERE (`id` = 1)")void update(Company company);
​@Override@Select("select * from company_information where id = #{id}")List<Company> findID(Company company);
​@Override@Select("select * from company_information ")List<Company> findAll(Company company);
}

service接口

/*** 公司service接口*/
public interface CompanyService extends BaseSerice<Company>{
}

service实现类

/*** 公司service实现类*/
@Service
public class CompanyServiceImpl implements CompanyService {@Autowiredprivate CompanyDao companyDao;@Overridepublic List<Company> findAll(Company o) {List<Company> list = new ArrayList<>();list = companyDao.findAll(o);return list;}
​@Overridepublic List<Company> findID(Company o) {List<Company> id = companyDao.findID(o);return id;}
}

三,springboot 如何实现自动装配

补充1:pagehelper的使用

使用pagehelper助手,其sql语句并不会直接发送给到数据库进行查询,而是会先经过mybatis的拦截器,拦截器会截取sql语句。

如:String sql = select * from users 对这句sql进行分页查询时

拦截器会拦截这句sql,转变为 String sql = select * from users limit (curPage-1)*pageSize,pageSize 然后再进行查询。

是一种实际的查询,并不是把所有数据查到放于内存中,在内存里进行分页输出。

补充2:beanFactory和factoryBean 的区别

区别:BeanFactory是个Factory,也就是IOC容器或对象工厂,FactoryBean是个Bean。在Spring中,所有的Bean都是由BeanFactory(也就是IOC容器)来进行管理的。但对FactoryBean而言,这个Bean不是简单的Bean,而是一个能生产或者修饰对象生成的工厂Bean,它的实现与设计模式中的工厂模式和修饰器模式类似

自动装配

根据名字实现自动装配是@EnableAutoConfiguration注解,点击进来。

.再点进

图中loadmetadata的方法是加载项目的基本配置数据信息,而getAutoConfigurationEntry方法则是自动装配的逻辑,继续点进去

protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return EMPTY_ENTRY;}AnnotationAttributes attributes = getAttributes(annotationMetadata);//这里加载了文件List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);configurations = removeDuplicates(configurations);Set<String> exclusions = getExclusions(annotationMetadata, attributes);checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations = getConfigurationClassFilter().filter(configurations);fireAutoConfigurationImportEvents(configurations, exclusions);return new AutoConfigurationEntry(configurations, exclusions);
}

方法中加载文件

其实到这一步基本清楚了,做的这些事情都是在加载类,那么自动装配到底加载的是什么类呢,这里从外部传入的factoryname是Enableautoconfiguration.class

点进去加载逻辑可以看到是在加载FACTORIES_RESOURCE_LOCATION路径下的类。

会自动扫描所有项目下FACTORIES_RESOURCE_LOCATION这个路径下的类,那么这个路径是啥?

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
总结:

到这里基本清楚了,springboot的自动装配就是通过自定义实现ImportSelector接口,从而导致项目启动时会自动将所有项目META-INF/spring.factories路径下的配置类注入到spring容器中,从而实现了自动装配。

相关的starter和自定义starter都是根据这个实现的。后续有空的话还会写一下如何实现自定义starter的随笔。 系统默认的META-INF/spring.factories路径下配置为

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
​
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer
​
# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor
​
# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
​
# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
​
# Auto Configure

相关文章:

Springboot 实战运用

一&#xff0c;基本配置 1&#xff0c;pom文件配置介绍 1.1继承 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.2</version><relativePath/> <…...

kafka的安装与简单使用

下载地址&#xff1a;Apache Kafka 1. 上传并解压安装包 tar -zxvf kafka_2.13-3.6.2.tgz 修改文件名&#xff1a;mv kafka_2.13-3.6.2 kafka 2. 配置环境变量 sudo vim /etc/profile #配置kafka环境变量 export KAFKA_HOME/export/server/kafka export PATH$PATH:$KAFKA…...

【服务器部署篇】Linux下Node.js的安装和配置

作者介绍&#xff1a;本人笔名姑苏老陈&#xff0c;从事JAVA开发工作十多年了&#xff0c;带过刚毕业的实习生&#xff0c;也带过技术团队。最近有个朋友的表弟&#xff0c;马上要大学毕业了&#xff0c;想从事JAVA开发工作&#xff0c;但不知道从何处入手。于是&#xff0c;产…...

【OrangePi AIpro】香橙派 AIpro 为AI而生

产品简介 OrangePi AIpro(8T)&#xff1a;定义边缘智能新纪元的全能开发板 在当今人工智能与物联网技术融合发展的浪潮中&#xff0c;OrangePi AIpro(8T)凭借其强大的硬件配置与全面的接口设计&#xff0c;正逐步成为开发者手中的创新利器。这款开发板不仅代表了香橙派与华为…...

AES算法

收集了几个博主 1、https://blog.csdn.net/shaosunrise/article/details/80219950 2、AESECB加密算法 C 语言代码实现_c语言aes-256-cbc-CSDN博客 3、https://www.cnblogs.com/hello-/articles/8718186.html 4、AES加密过程详解-CSDN博客 5、AES加密算法原理的详细介绍与实…...

自主创新助力科技强军,麒麟信安闪耀第九届军博会

由中国指挥与控制学会主办的中国指挥控制大会暨第九届北京军博会于5月17日-19日在北京国家会议中心盛大开展&#xff0c;政府、军队、武警、公安、交通、人防、航天、航空、兵器、船舶、电科集团等从事国防军工技术与产业领域的30000多名代表到场参加。 麒麟信安作为国产化方案…...

Android Retrofit 封装模版

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、加上网络访问的权限二、引入依赖三、由API生成JavaBean四、封装Retrofit五、调用 一、加上网络访问的权限 <uses-permission android:name"android.p…...

【介绍下运维开发】

&#x1f3a5;博主&#xff1a;程序员不想YY啊 &#x1f4ab;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f917;点赞&#x1f388;收藏⭐再看&#x1f4ab;养成习惯 ✨希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出…...

mybatis-plus中多条件查询使用and合or嵌套使用

背景 在实际项目中&#xff0c;数据库条件查询经常需有一些复杂的查询条件的SQL语句,将这些SQL语句用mybatis-plus 组件的实现的时候经常会费一些时间&#xff0c;下面对几种常见的SQL语句实现做个介绍以方便以后遇到时少走弯路提高开发效率。 案例 Data public class User{ …...

前端加密的方式汇总

目录 一、Base64编码 二、哈希算法 三、对称加密(AES/DES) 四、非对称加密(RSA) 五、加盐 六、Web Cryptography API 七、总结 随着信息和数据安全重要性的日益凸显&#xff0c;如何保证信息数据在传输的过程中的安全成为开发者重点关注的内容。前端加密通常是指在浏览…...

ELT 同步 MySQL 到 Doris

如何基于 Flink CDC 快速构建 MySQL 到 Doris 的 Streaming ELT 作业&#xff0c;包含整库同步、表结构变更同步和分库分表同步的功能。 本教程的演示都将在 Flink CDC CLI 中进行&#xff0c;无需一行 Java/Scala 代码&#xff0c;也无需安装 IDE。 准备阶段 # 准备一台已经…...

100个 Unity小游戏系列七 -Unity 抽奖游戏专题五 刮刮乐游戏

一、演示效果 二、知识点讲解 2.1 布局 void CreateItems(){var rewardLists LuckyManager.Instance.CalculateRewardId(rewardDatas, Random.Range(4, 5));reward_data_list reward_data_list ?? new List<RewardData>();reward_data_list.Clear();for (int i 0; …...

链游:区块链技术的游戏新纪元

随着区块链技术的快速发展&#xff0c;越来越多的行业开始探索与其结合的可能性&#xff0c;其中&#xff0c;游戏行业与区块链的结合尤为引人注目。链游&#xff0c;即基于区块链技术的游戏&#xff0c;正以其独特的优势&#xff0c;为玩家带来全新的游戏体验。本文将对链游进…...

格式化字符串

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 格式化字符串是指先制定一个模板&#xff0c;在这个模板中预留几个空位&#xff0c;然后再根据需要填上相应的内容。这些空位需要通过指定的符号标记…...

错误信息:Traceback (most recent call last):

错误信息 Traceback (most recent call last): File "E:\python.learning\pythonDateExcavateTreat\数据挖掘课程设计\2_京东用户意向购买数据探索.py", line 74, in <module> df_ui df_ui.to_frame().reset_index() File "E:\python.learning\lib\site-…...

Thinkphp3.2.3网站后台不能访问如何修复

我是使用Thinkphp3.2.3新搭建的PHP网站&#xff0c;但是网站前台可以访问&#xff0c;后台访问出现如图错误&#xff1a; 由于我使用的Hostease的Linux虚拟主机产品默认带普通用户权限的cPanel面板&#xff0c;对于上述出现的问题不清楚如何处理&#xff0c;因此联系Hostease的…...

Golang 如何使用 gorm 存取带有 emoji 表情的数据

Golang 如何使用 gorm 存取带有 emoji 表情的数据 结论&#xff1a;在 mysql 中尽量使用 utf8mb4&#xff0c;不要使用 utf8。db报错信息&#xff1a;Error 1366 (HY000): Incorrect string value: \\xE6\\x8C\\xA5\\xE7\\xAC\\xA6...根本原因&#xff1a;emoji 4个字节&#x…...

计算机算法中的数字表示法——原码、反码、补码

目录 1.前言2.研究数字表示法的意义3.数字表示法3.1 无符号整数3.2 有符号数值3.3 二进制补码(Twos Complement, 2C)3.4 二进制反码(也称作 1 的补码, Ones Complement, 1C)3.5 减 1 表示法(Diminished one System, D1)3.6 原码、反码、补码总结 1.前言 昨天有粉丝让我讲解下定…...

BGP策略实验

一、实验要求 二、实验分析 1.先配置IP 2.再配置BGP 3.配置BGP策略 三、实验过程 要求 1. [r4]ip ip-prefix aa permit 192.168.10.0 24 [r4]route-policy aa permit node 10 [r4-route-policy]if-match ip-prefix aa [r4-route-policy]apply preferred-value 100 [r4]rout…...

目标检测 | R-CNN、Fast R-CNN与Faster R-CNN理论讲解

☀️教程&#xff1a;霹雳吧啦Wz ☀️链接&#xff1a;https://www.bilibili.com/video/BV1af4y1m7iL?p1&vd_sourcec7e390079ff3e10b79e23fb333bea49d 一、R-CNN R-CNN&#xff08;Region with CNN feature&#xff09;是由Ross Girshick在2014年提出的&#xff0c;在PAS…...

【busybox记录】【shell指令】mkdir

目录 内容来源&#xff1a; 【GUN】【mkdir】指令介绍 【busybox】【mkdir】指令介绍 【linux】【mkdir】指令介绍 使用示例&#xff1a; 创建文件夹 - 默认 创建文件夹 - 创建的同时指定文件权限 创建文件夹 - 指定多级文件路径&#xff0c;如果路径不存在&#xff0c…...

SQL刷题笔记day6-1

1从不订购的客户 分析&#xff1a;从不订购&#xff0c;就是购买订单没有记录&#xff0c;not in 我的代码&#xff1a; select c.name as Customers from Customers c where c.id not in (select o.customerId from Orders o) 2 部门工资最高的员工 分析&#xff1a;每个部…...

KITTI数据中pose含义

Folder ‘poses’: The folder ‘poses’ contains the ground truth poses (trajectory) for the first 11 sequences. This information can be used for training/tuning your method. Each file xx.txt contains a N x 12 table, where N is the number of frames of this …...

C++模拟实现stack和queue

1 stack 1.1概念 stl栈 1.2栈概念 1.3代码 2 queue 2.1概念 stl队列 2.2队列概念 2.3代码...

awtk踩坑记录一:awtk-web build.py编译过程笔记

工作需求&#xff0c;接触了awtk, 要求把界面部署到web上&#xff0c;期间因为各种编译问题卡的半死&#xff0c;提了不少issue, 经过几天补课&#xff0c;把项目的编译结构给摸了一遍&#xff0c;做个记录&#xff0c;也希望能帮到有同样问题的朋友。 之前python只是略接触过…...

docker容器中解决中文乱码

1. 找到dockerfile文件 2. 编辑Dockerfile 添加 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 3. 生成新的镜像文件 FROM java17_yinpeng:latest MAINTAINER YP <2064676101QQ.COM> ADD jiquan_online_chat.jar jiquan_online_chat #CM…...

Javascript 位运算符(,|,^,<<,>>,>>>)

文章目录 一、什么是位运算&#xff1f;二、如何使用1. 位与&#xff08;AND&#xff09;&#xff1a;&用途&#xff08;1&#xff09;数据清零&#xff08;2&#xff09;判断奇偶 2. 位或&#xff08;OR&#xff09;&#xff1a;|用途&#xff08;1&#xff09;向下取整 3…...

Golang项目代码组织架构实践

Golang在项目结构上没有强制性规范&#xff0c;虽然这给了开发者很大的自由度&#xff0c;但也需要自己沉淀一套可行的架构。本文介绍了一种项目布局&#xff0c;可以以此为参考设计适合自己的 Golang 项目组织模式。原文: Golang Project Layout Go 有很多强制的或是约定俗成的…...

网工内推 | 国企信息安全工程师,CISP认证优先

01 浙江省公众信息产业有限公司 &#x1f537;招聘岗位&#xff1a;安全运营工程师 &#x1f537;职责描述&#xff1a; 1. 负责公司内部安全运营平台及其子系统的安全事件管理、事件发现分析、应急响应和系统维护等&#xff1b; 2. 负责风险和漏洞管理&#xff0c;包括漏洞预…...

RAG 高级应用:基于 Nougat、HTML 转换与 GPT-4o 解析复杂 PDF 内嵌表格

一、前言 RAG&#xff08;检索增强生成&#xff09;应用最具挑战性的方面之一是如何处理复杂文档的内容&#xff0c;例如 PDF 文档中的图像和表格&#xff0c;因为这些内容不像传统文本那样容易解析和检索。前面我们有介绍过如何使用 LlamaIndex 提供的 LlamaParse 技术解析复…...