springboot笔记总结

2023-11-05

springboot

1. Javaconfig

@Configuration:放在类的上面, 这个类相当于 xml 配置文件,可以在其中声明 bean

@Bean:放在方法的上面, 方法的返回值是对象类型, 这个对象注入到 spring ioc 容器

@ImportResource 是导入 xml 配置,等同于 xml 文件的 resources

@PropertyResource 是读取 properties 属性配置文件

2. spring boot入门

2.1 基本注解

@SpringBootApplication : @SpringBootApplication 是 一 个 复 合 注 解 , 是 由

@SpringBootConfiguration, @EnableAutoConfiguration ,@ComponentScan 联合在一起组

成的。

@SpringBootConfiguration : 就 是 @Configuration 这 个 注 解 的 功 能 , 使 用

@SpringBootConfiguration 这个注解的类就是配置文件的作用。

@EnableAutoConfiguration:开启自动配置, 把一些对象加入到 spring 容器中。

@ComponentScan:组件扫描器, 扫描注解,根据注解的功能,创建 java bean,给属性赋值

等等。组件扫描器默认扫描的是 @ComponentScan 注解所在的类, 类所在的包和子包。

2.2 多环境

为每个环境创建一个配置文件,命名必须以 application-环境标识.properties|yml

application.properties(在这里指定使用的环境文件)

spring.profiles.active=test

2.3 注解

2.3.1 @Value

@Value(“${key}”) , key 来自 application.properties(yml)

application.properties

school.name=动力节点
school.address=北京大兴区
school.website=www.bjpowernode.com

读取配置文件数据

@Value("${server.port}")
 private String port;

2.3.2 @ConfigurationProperties

将整个文件映射成一个对象,用于自定义配置项比较多的情况

创建 SchoolInfo 类,并为该 类加上Component 和 ConfigurationProperties 注解,prefix 可以不指定,如果不指定,那么会去配置文件中寻找与该类的属性名一致的配置,prefix 的作用可以区分同名配置

application.properties

school.name=动力节点
school.address=北京大兴区
school.website=www.bjpowernode.com
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
 private String name;
 private String address;
 private String website;
 // set | get 方法
}
@Resource
 private SchoolInfo schoolInfo;

2.4 JSP

1.添加依赖

<!--如果只是使用 JSP 页面,可以只添加该依赖-->
<dependency>
 <groupId>org.apache.tomcat.embed</groupId>
 <artifactId>tomcat-embed-jasper</artifactId>
</dependency>


<!--如果要使用 servlet 必须添加该以下两个依赖-->
<!-- servlet 依赖的 jar 包-->
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- jsp 依赖 jar 包-->
<dependency>
 <groupId>javax.servlet.jsp</groupId>
 <artifactId>javax.servlet.jsp-api</artifactId>
 <version>2.3.1</version>
</dependency>

<!--如果使用 JSTL 必须添加该依赖-->
<!--jstl 标签依赖的 jar 包 start-->
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
</dependency

2.配置build

<resources>
 <resource>
 <!--源文件位置-->
 <directory>src/main/webapp</directory>
 <!--指定编译到META-INF/resource,该目录不能随便写-->
 <targetPath>META-INF/resources</targetPath>
 <!--指定要把哪些文件编译进去,**表示 webapp 目录及子
目录,*.*表示所有文件-->
 <includes>
 <include>**/*.*</include>
 </includes>
 </resource>
</resources>

3.配置springmvc

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

4.创建JspController 类

@Controller
public class SpringBootController {
 @RequestMapping(value = "/springBoot/jsp")
 public String jsp(Model model) {
 model.addAttribute("data","SpringBoot 前端使用 JSP页面!");
 return "index";
 } 
}

5.创建webapp

在该目录下新建index.jsp页面

6.jsp 中获取 Controller 传递过来的数据

3. springboot 和 web组件

3.1 拦截器

1.创建类实现 HandlerInterceptor 接口

public class LoginInterceptor implements HandlerInterceptor {
 @Override
 public boolean preHandle(HttpServletRequest request, 
HttpServletResponse response, Object handler) throws Exception {
 System.out.println("执行了 LoginInterceptor,preHandle()");
 return true;
 } 
}

2.注册拦截器

@Configuration
public class MyAppConfig implements WebMvcConfigurer {
 //注册拦截器对象的
 @Override
 public void addInterceptors(InterceptorRegistry registry) {
 // InterceptorRegistry 登记系统中可以使用的拦截器
 // 指定拦截的地址
 String path [] = {"/user/**"};
 String excludePath [] = {"/user/login"};
 registry.addInterceptor( new LoginInterceptor())
 .addPathPatterns(path).excludePathPatterns(excludePath);
 } }

3.创建测试controller

@Controller
public class BootController {
 @RequestMapping("/user/account")
 @ResponseBody
 public String queryAccount(){
 return "user/account";
 }
 @RequestMapping("/user/login")
 @ResponseBody
 public String login(){
 return "/user/login";
 } }

3.2 Servlet

1.创建Servlet

public class MyServlet extends HttpServlet {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
 doPost(req,resp);
 }
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
 resp.setContentType("text/html;charset=utf-8");
 PrintWriter out = resp.getWriter();
 out.println("使用 Servlet 对象");
 out.flush();
 out.close();
 } 
}

2.注册Servlet

@Configuration
public class SystemConfig {
 @Bean
 public ServletRegistrationBean servletRegistrationBean(){
 ServletRegistrationBean reg = new ServletRegistrationBean(
 new MyServlet(),"/loginServlet");
 return reg;
 } 
}

3.3 Filter

1.创建Filter对象

public class MyFilter implements Filter {
 @Override
 public void doFilter(ServletRequest servletRequest,
 ServletResponse servletResponse,
 FilterChain filterChain) throws IOException, 
ServletException {
 System.out.println("使用了 Servlet 中的 Filter 对象");
 filterChain.doFilter(servletRequest,servletResponse);
 } 
}

2.注册Filter

@Configuration
public class SystemConfig {
 @Bean
 public FilterRegistrationBean filterRegistrationBean(){
 FilterRegistrationBean reg = new FilterRegistrationBean();
 //使用哪个过滤器
 reg.setFilter( new MyFilter());
 //过滤器的地址
 reg.addUrlPatterns("/user/*");
 return reg;
 } }

3.创建Controller

@Controller
public class FilterController {
 @RequestMapping("/user/account")
 @ResponseBody
 public String hello(){
 return "/user/account";
 }
 @RequestMapping("/query")
 @ResponseBody
 public String doSome(){
 return "/query";
 }
}

3.4 字符集过滤器

application.properties 文件中设置过滤器

Spring Boot 项目默认启用了 CharacterEncodingFilter, 设置他的属性就可以

#设置 spring boot 中 CharacterEncodingFitler 的属性值
server.servlet.encoding.enabled=true 
server.servlet.encoding.charset=utf-8 
#强制 request, response 使用 charset 他的值 utf-8
server.servlet.encoding.force=true

4. MySQL

4.1 过程

1.配置

<!--mybatis 起步依赖: mybatis 框架需要的依赖全部加入好-->
 <dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>2.1.4</version>
 </dependency>


 <!--mysql 驱动-->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <scope>runtime</scope>
 </dependency>

 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
 </dependency>
</dependencies>


<!--加入 resource 插件--> <resources>
 <resource>
 <directory>src/main/java</directory>
 <includes>
 <include>**/*.xml</include>
 </includes>
 </resource>
</resources>

2.配置数据源

#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8

#serverTimezone=Asia/Shanghai

spring.datasource.username=root
spring.datasource.password=123

4.2 @MapperScan

在 Dao 接口上面加入@Mapper,需要在每个接口都加入注解。

当 Dao 接口多的时候不方便。可以使用如下的方式解决。主类上添加注解包扫描:@MapperScan(“com.bjpowernode.dao”)

4.3 mapper文件和java代码分开管理

这种方式比较推荐,mapper 文件放在 resources 目录下, java 代码放在 src/main/java。

在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映

射文件不在同一个包的情况下,才需要指定。

mybatis:
 mapper-locations: classpath:mapper/*.xml
 configuration:
 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.4 事务支持

➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持

➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可

5. RESTful-接口架构风格

5.1 注解

5.1.1 @PathVariable

获取 url 中的数据

属性: value : 路径变量名称

位置: 在逐个接收参数中,在形参定义的前面

注意:路径变量名和形参名一样, value 可以不写

5.1.2 @PostMapping

接收和处理 Post 方式的请求

5.1.3 @DeleteMapping

接收 delete 方式的请求,可以使用 GetMapping 代替

5.1.4 @PutMapping

接收 put 方式的请求,可以用 PostMapping 代替

5.1.5 @GetMapping

接收 get 方式的请求

5.2 演示

@GetMapping(value = "/student/{studentId}/{classname}")
 public String queryStudent(
     @PathVariable(value = "studentId") Integer id,
     @PathVariable String classname){
 return "get 请求,查询学生 studentId:"+id+", 班级:"+classname;
 }
 ///student/1001/bjpowernode


 @GetMapping(value = "/student/{studentId}/school/{schoolname}")
 public String queryStudentBySchool(@PathVariable(value = "studentId") 
Integer id,
 @PathVariable String schoolname){
 return "get 请求,查询学生 studentId:"+id+", 班级:"+schoolname;
 }



 @PostMapping("/student/{stuId}")
 public String createStudent(@PathVariable("stuId") Integer id,
 String name,
 Integer age){
 return "post 创建学生, id="+id+",name="+name+",age="+age;
 }


 @PutMapping("/student/{stuId}")
 public String modifyStudent(@PathVariable("stuId") Integer id,
 String name){
 System.out.println("===========put 请求方式 ========");
 return "put 修改学生, id="+id+",修改的名称是:"+name;
 }


 @DeleteMapping("/student/{stuId}")
 public String removeStudent(@PathVariable("stuId") Integer id){
 System.out.println("===========delete 请求方式 ========");
 return "delete 删除学生,id="+id;
 } 
}

application.properties 文件

server.servlet.context-path=/myboot
启用 HiddenHttpMethodFilter 这个过滤器, 支持 post 请求转为 put,delete
spring.mvc.hiddenmethod.filter.enabled=true

设计路径,必须唯一, 路径 uri 和 请求方式必须唯一。

6. 集成Redis

Redis 是一个 NoSQL 数据库, 常作用缓存 Cache 使用。 通过 Redis 客户端可以使用多种

语言在程序中,访问 Redis 数据。java 语言中使用的客户端库有 Jedis,lettuce, Redisson

等。

Spring Boot 中使用 RedisTemplate 模版类操作 Redis 数据。

需求:完善根据学生 id 查询学生的功能,先从 redis 缓存中查找,如果找不到,再从数

据库中查找,然后放到 redis 缓存中

1.添加依赖

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.核心配置文件 application.properties

#指定 redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456

3.创建 RedisController

@RestController
public class RedisController {
 //注入 RedisTemplate
 //泛型 key,value 都是 String ,或者 Object, 不写
 @Resource
 private RedisTemplate redisTemplate;
 @GetMapping("/myname")
 public String getName(){
 redisTemplate.setKeySerializer( new StringRedisSerializer());
 // redisTemplate.setValueSerializer( new StringRedisSerializer());
 String name=(String) redisTemplate.opsForValue().get("name");
 return name;
 }
 @PostMapping("/name/{myname}")
 public String addName(@PathVariable("myname") String name){
 redisTemplate.opsForValue().set("name",name);
 return "添加了学生:"+name;
 } }

4.启动redis服务

7. 集成Dubbo

7.1 创建接口module

01:普通maven项目

1.model类

public class Student implements Serializable {
 private Integer id;
 private String name;
 private Integer age;
 //set|get 方法
}

2.服务接口

public interface StudentService {
 Student queryStudent(Integer studentId);
}

7.2 服务提供者module

02:springboot 无依赖

1.添加依赖

<dependency>
 <groupId>org.apache.dubbo</groupId>
 <artifactId>dubbo-dependencies-zookeeper</artifactId>
 <version>2.7.8</version>
 <type>pom</type>
</dependency

2.application.properties

#服务名称
spring.application.name=service-provider

#zookeeper 注册中心
dubbo.registry.address=zookeeper://localhost:2181

#dubbo 注解所在的包名
dubbo.scan.base-packages=com.bjpowernode.service

3.创建接口实现类

@Component
@DubboService(interfaceClass = StudentService.class,version = "1.0")
public class StudentServiceImpl implements StudentService {
 @Override
 public Student queryStudent(Integer studentId) {
 Student student = new Student();
 student.setId(studentId);
 student.setName("张三");
 student.setAge(20);
 return student;
 }
}

4.主启动类上加@EnableDubbo

7.3 创建消费者module

03:springboot web依赖

1.添加依赖

<dependency>
 <groupId>org.apache.dubbo</groupId>
 <artifactId>dubbo-spring-boot-starter</artifactId>
 <version>2.7.8</version>
</dependency>

<dependency>
 <groupId>org.apache.dubbo</groupId>
 <artifactId>dubbo-dependencies-zookeeper</artifactId>
 <version>2.7.8</version>
 <type>pom</type>
</dependency>

2.application.properties

#服务名称
spring.application.name=service-consumer

#dubbo 注解所在的包
dubbo.scan.base-packages=com.bjpowernode

#zookeeper
dubbo.registry.address=zookeeper://localhost:2181

3.创建MyController

@RestController
public class MyController {
 @DubboReference(interfaceClass = StudentService.class,version = 
"1.0",check = false)
 private StudentService studentService;
 @GetMapping("/query")
 public String searchStudent(Integer id){
 Student student = studentService.queryStudent(id);
 return "查询学生:"+ student.toString();
 }
}

4.主启动类上加@EnableDubbo

7.4 测试

1)先启动 zookeeper

2)运行服务提供者 02-service-provider

3)运行消费者 03-consumer

4)在浏览器执行 http://localhost:8080/query?id=1

日志依赖 SLF4j 多次加入了。只需要依赖一次就可以。

解决方式:排除多余的 SLF4j 依赖, 提供者和消费者项目都需要这样做

<dependency>
 <groupId>org.apache.dubbo</groupId>
 <artifactId>dubbo-dependencies-zookeeper</artifactId>
 <version>2.7.8</version>
 <type>pom</type>
 <exclusions>
 <exclusion>
 <artifactId>slf4j-log4j12</artifactId>
 <groupId>org.slf4j</groupId>
 </exclusion>
 </exclusions>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot笔记总结 的相关文章

随机推荐

  • node、npm、cnpm踩坑

    文章目录 前言 一 cnpm i 报错无法使用 二 解决步骤 1 查看cnpm 是否安装 2 查看 node 和 npm 版本 3 处理 总结 前言 提示 npm install g cnpm registry https registry
  • vue项目请求控制请求头必须为https

    前言 因为很多项目必须要求是严格模式 不能有http请求 需要限制我们的请求头必须为https 如果是http的话 手动转成https来实现请求效果 实现方法 在 public index html 的 head 标签里面加入以下代码 效果
  • Step4:Angular调试方法

    1 方法一 采用VSCode编译器 下载插件debugger for chrome 选择调试 然后再选择chrome浏览器 在运行中输入npm start执行 就可以在代码中打断点了 2 方法二 在浏览器中按F12打开开发者工具 Sourc
  • Python第二课

    枭 Python第二课 今天讲解了Python的 内置函数 模块导入 序列 列表 切片操作 内置函数 divmod x y 用法 x y divmod a b 其中x返回值a b y返回值a b map func iterablies 用法
  • 4g网络设置dns地址_4G网速越来越慢,通过这三个简单的操作,网速成倍提升

    随着互联网的进步 从零几年开始移动手机在全国开始普及起来 网速也像火箭一样快速飙升 从2G发展到了现在的5G 不过 有很多网友表示 刚从2G或者3G升级到4G时 网速体验非常好 但近两年来的4G网速越来越慢 还卡顿 甚至感觉还不如以前的3g
  • 忘记网站服务器密码怎么办,忘记远程服务器的密码怎么办

    忘记远程服务器的密码怎么办 内容精选 换一换 如果在创建弹性云服务器时未设置密码 或密码丢失 过期 可以参见本节操作重置密码 密码丢失或过期前 已安装密码重置插件 公共镜像创建的弹性云服务器默认已安装一键重置密码插件 私有镜像创建的云服务器
  • Matlab—M_Map的实战学习笔记(一)M_Map库的安装

    最近在做美赛集训 做到了2020年的美赛A题 有关苏格兰附近鲭鱼和鲱鱼分布预测问题 在写论文的过程中 为了画几张精美的地图 可谓是历经千难万险 花费了不少时间 走了不少弯路 现在对使用matlab的m map映射库进行地图绘制做一个总结 力
  • Python:UnicodedecodeError编码问题解决方法汇总-彻底解决

    今天真的被编码问题一直困扰着 午休都没进行 也真的见识到了各种编码 例如 gbk unicode utf 8 ansi gb2312等 如果脚本程序中编码与文件编码不一致 就会报出UnicodedecodeError的错误 1 情景一 读文
  • python语法-面向对象(构造方法、魔术方法)

    python语法 面向对象 构造方法 魔术方法 1 构造方法 构造方法 python类可以使用 init 方法 称之为构造方法 可以实现 在创建类对象时 会自动执行 在创建类对象时 将传入参数自动传递给 init 方法使用 演示使用构造方法
  • Android中的定时器Timer、AlarmManager、CountDownTimer的使用

    1 Timer和TimerTask的使用 java util Timer定时器 实际上是个线程 定时调度所拥有的TimerTasks 1 创建一个Timer code class hljs cs has numbering style di
  • 解析 Linux 内核可装载模块的版本检查机制

    解析 Linux 内核可装载模块的版本检查机制 王 华东 系统工程师 自由职业者 简介 为保持 Linux 内核的稳定与可持续发展 内核在发展过程中引进了可装载模块这一特性 内核可装载模块就是可在内核运行时加载到内核的一组代码 通常 我们会
  • js获取到的时间减1秒或加1秒

    如题 使用时间戳来计算 function setDate time isAdd var date getCurTime time 也可以直接透传如 2021 5 8 var d new Date date var t s d getTime
  • 闲鱼把各种玩法做成了一个平台:哆啦A梦

    玩法平台背景 在闲鱼内我们把供给用户的闲鱼红包 支付宝红包 包邮券 宝卡等统称为用户权益 是闲鱼用户运营的重要策略 在拉新 留存 促活 裂变等方面都展现了其重要价值 在阿里内部管理权益的平台是拉菲 拉菲对外提供概率抽奖和领奖两种能力 各个业
  • 为什么gbk编码常用抽取正则表达式无法抽取“嘚瑟“的“嘚”字

    根据 GBK汉字内码扩展规范编码表 http ff 163 com newflyff gbk list 可以查到 嘚 字的编码为874e 而我们常用的gbk汉字抽取正则表达式为 x80 xff x80 xff 以python正则为例 抽取汉
  • Python基础--入门基础和数据类型测试题(二)

    Made By Zly All Right Reversed 上一篇 篇四 Python 入门基础和数据类型测试题 二 1 以下不属于Python语言保留字的是 A do B pass C while D def 2 表达式3 4 2 8
  • 第一讲 检索系统与数据库编程

    第一讲 检索系统与数据库编程 准备工作 1 检索系统 1 1 检索系统初识 1 1 1 什么是检索系统 1 1 2 从认知心理学看待检索系统 1 2 检索系统的四大法宝 1 2 1 检索的工具 结构化查询语言 SQL 1 2 2 检索的环境
  • Electron-builder打包和自动更新

    前言 文本主要讲述如何为 electron 打包出来软件配置安装引导和结合 github 的 release 配置自动更新 electron builder 是将 Electron 工程打包成相应平台的软件的工具 我的工程是使用 elect
  • C语言小知识点

    1 LPCSTR被定义成是一个指向以 0 结尾的常量字符指针 LPWSTR是wchar t字符串 例子 LPWSTR lpwstr NULL LPWSTR lp T asdfasgaf 2 之所以能够实现条件编译是因为预编译指令是在编译之前
  • HTTP请求头和响应头详解【转】

    最近老猿在开始学习爬虫相关的知识 由于老猿以前只做非web的后台应用 发现相关知识太过匮乏 导致学习很困难 为此不得不从一些基础知识恶补开始 对于这些知识 老猿会将网上找到的比较认可的内容直接转发 下面文章关于http头部信息讲解的非常详细
  • springboot笔记总结

    springboot 1 Javaconfig Configuration 放在类的上面 这个类相当于 xml 配置文件 可以在其中声明 bean Bean 放在方法的上面 方法的返回值是对象类型 这个对象注入到 spring ioc 容器