SpringBoot笔记

SpringBoot框架

0.0为什么使用SpringBoot

1.为什么使用Spirngboot 因为Spring,Springmvc需要大量的配置文件(xml文件)

还需要配置各种对象,把使用的对象放入到Spring容器内中才能使用对象

还得需要了解其他框架的配置规则

2.SpirngBoot就相当于不需要配置文件的Spirng+SpringMvc。常用的框架和第三方库都已经配置好了。拿来用即可。

3.SpirngBoot开发效率高,使用方便

第一章xml和JavaConfig

Spring使用xml作为容器配置文件,在3.0以后加入了JavaConfig,使用java类做配置

1.1.1什么是javaConfig

JavaConfig:是spring提供的使用Java类做配置容器,配置SpringIoc容器纯Java方法

优点:

  1. 可以使用面向对象的方式,一个配置类可以继承配置类,可以重写方法.

  2. 避免繁琐的xml配置

使用两个注解的支持

  1. @Configuration:放在一个类的类名上面,表示这个类是作为配置文件使用.

  2. @Bean:声明对象,把对象注入到容器中.

package com.prg.config;

import com.prg.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* Configuration:表示当前类是配置文件类(配置容器的)
* 位置:在类名上方添加
* SpringConfig == beans.xml
*/
@Configuration
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象,在方法上面添加@Bean
* 方法的返回值就注入到容器中
*
* @Bean:把对象注入到spring容器中,作用相当于<bean></bean>
* 位置:在方法的上面添加
*
*   说明: @bean 不指定对象名,它默认是方法名 == id
*
*   */
@Bean
public Student createStudent(){
   Student students = new Student();
   students.setName("甘雨");
   students.setAge(18);
   students.setSex("女");
   return  students;

}

/**
* 指定对象在容器中的名称(指定<bean></bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@Bean(name = "listStudent")
public Student makeStudent(){
   Student students = new Student();
   students.setName("凝光");
   students.setAge(19);
   students.setSex("女");
   return  students;

}
}

 

1.1.2@ImportResource

@ImportResource作用是导入其他配置文件,等于在xml中的

<import resources="其他配置文件" />

例如:

@ImportResource({"classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {

}

 

 

1.1.3@PropertyResource

作用读取属性配置文件:properties

在resoureces目录下创建 config.properties

==xml中的扫描器

步骤:

  1. 在resoureces目录下创建 config.properties文件,使用k=v的格式提供数据

  2. 在PropertyResiurce指定properties文件的位置

  3. 使用@Value(value = "${key}")

@Configuration
@ImportResource({"classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource("classpath:config.properties")
@ComponentScan(basePackages = "com.prg.vo")
public class SpringConfig {
}

 

第二章SpringBoot

2.2.1介绍

SpringBoot是Spring中的一个成员,可以简化SpringSpringmvc的使用,他的核心还是IOC容器

  • 创建独立的 Spring 应用程序

  • 直接嵌入 Tomcat、Jetty 或 Undertow(无需部署 WAR 文件)

  • 提供自以为是的“入门”依赖项以简化您的构建配置

  • 尽可能自动配置 Spring 和 3rd 方库

  • 提供生产就绪功能,例如指标、健康检查和外部化配置

  • 完全无需代码生成,无需 XML 配置

  • Create stand-alone Spring applications

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

  • Provide opinionated 'starter' dependencies to simplify your build configuration

  • Automatically configure Spring and 3rd party libraries whenever possible

  • Provide production-ready features such as metrics, health checks, and externalized configuration

  • Absolutely no code generation and no requirement for XML configuration

 

2.2.2创建SpringBoot项目

**2.2.2.1第一方式,使用Spring提供的初始化器,就是向导创建SpringBoot应用

SpringBoot项目结构

image-20220320211447286

 

 

image-20220320212331972

 

 

2.2.2.2第二种方式使用国内的地址进行创建

 

image-20220320212617700

 

@SpringBootApplication:(注解的使用)

@SpringBootConfiguration

@SpringBootApplication
符合注解:

@SpringBootConfiguration
 @Configuration
public @interface SpringBootConfiguration {
   @AliasFor(
       annotation = Configuration.class
  )
   boolean proxyBeanMethods() default true;
}
  //说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,可以使用Bean声明对象,注入到容器中.
   
@EnableAutoConfiguration
@ComponentScan(
   excludeFilters = {@Filter(
   type = FilterType.CUSTOM,
   classes = {TypeExcludeFilter.class}
), @Filter(
   type = FilterType.CUSTOM,
   classes = {AutoConfigurationExcludeFilter.class}
)}
)

 

 

@EnableAutoConfiguration

启用自动配置,把java对象配置好,注入到spring容器中,例如可以把mybatis的对象创建好,放入到容器中.

@ComponentScan

扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等

它默认所扫描的包:@ComponentScan它所在的类所在的包和子包。

 

2.2.4SpringBoot配置文件

配置文件名:application;

扩展名: properties(k=v);yml(k: v)

使用:application.properties;application.yml

例1:application.prperties设置上下文访问路径和端口号

#自定义端口号
server.port=8084
#设置访问应用上下文路径:contextPath
server.servlet.context-path=/MyBoot

 

例2:applicaiton.yml

server:
port: 8083
servlet:
  context-path: /Myboot2

2.2.5多环境配置

多环境: 开发环境 测试环境 上线环境

每个环境都有不同德配置信息,例如端口、上下文件、数据url、用户名、密码等等

使用多环境配置文件可以方便切换不同的配置

使用方式:创建多个配置文件,名称规则:appplication-环境名称.properties(yml)

创建一个开发环境的配置文件: application-dev.properties(yml)

创建一个测试环境的配置文件:application-test.properties(yml)

#激活环境配置文件
#激活开发环境的配置文件
#spring.profiles.active=dev
#激活测试环境的配置文件
spring.profiles.active=test

 

 

 

2.2.6

 

 

2.2.7使用JSP

SpringBoot不推荐使用jsp,而是使用模板技术代替JSP

使用JSP

1.添加一个处理JSP的依赖,负责编译jsp文件 <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId>

</dependency>

 

 

2.如果使用servlet,jsp,jstl功能所用的依赖

<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>javax.servlet.jsp-api</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
   <groupId>javax.servlet.jsp.jstl</groupId>
   <artifactId>jstl</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
</dependency>



3.创建一个存放jsp的目录,一般叫webapp

 

4.需要在pom.xml指定jsp文件编译后的存放目录

META-INF/resources

5.创建Controller,访问jsp

6.在application.properties配置视图解析器

 

 

2.2.8使用容器

通过SpringAppplication.run

 

2.2.9ComnandLineRunner接口, ApplicationRunner接口

这两个接口都有一个run方法,执行时间在容器对象创建好之后,自动执行run()方法

可以完成自定义的在容器对象创建好的一些操作

 

public interface ApplicationRunner {
  void run(ApplicationArguments args) throws Exception;
}

@FunctionalInterface
public interface CommandLineRunner {
  void run(String... args) throws Exception;
}

 

 

第三章Web组件

三内容: 拦截器 Servlet Filter

3.1.1拦截器

拦截器是SpringMvc中的一种对象,能拦截对Controller的请求

拦截器框架中有系统的拦截器,还可以自定义拦截器。实现对请求预先处理

 

实现自定义拦截器:

1.创建类实现springmvc框架的HandlerInterceptor接口

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;

public interface HandlerInterceptor {
   default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       return true;
  }

   default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
  }

   default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
  }
}

 

 

2.需要在Springmvc的配置文件中,声明拦截器

<mvc:interceptors>
<mvc:interceptor>
  <mvc:path="url" />
       <bean class="拦截器类全限定名称" />
   </mvc:interceptor>
</mvc:interceptors>

 

 

3.在SpringBoot框架中注册拦截器:

@Configuration
public class MyAppConfig implements WebMvcConfigurer {

   //添加拦截器对象到容器中
   @Override
   public void addInterceptors(InterceptorRegistry registry) {

       //创建拦截器对象
       HandlerInterceptor interceptor = new LoginInterceptor();
       //指定拦截请求的url
       String [] path = {"/user/**"};
       //指定不拦截的url
       String [] excludePath = {"/user/login"};
       //添加拦截器
      registry.addInterceptor(interceptor)
              .addPathPatterns(path)
              .excludePathPatterns(excludePath);
  }
}

 

3.1.2过滤器Filter

FilterServlet规范中的过滤器,可以处理请求,对请求的参数,属性进行调整,常常在过滤器中处理字符编码

 

在框架中使用过滤器:

1.创建自定义过滤器类

public class MyFilter implements Filter {
   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       System.out.println("执行了MyFilter");
       filterChain.doFilter(servletRequest,servletResponse);
  }
}

2.注册Filter过滤对象

@Configuration
public class WebApplicationConfig {

   @Bean
   public FilterRegistrationBean filterRegistrationBean(){
       FilterRegistrationBean bean = new FilterRegistrationBean();
       bean.setFilter(new MyFilter());
       bean.addUrlPatterns("/user/*");
       return bean;
  }
}

3.1.3字符集过滤器

CharacterEncodingFilter:解决post请求中乱码的问题

SpringMVC的框架中,在web.xml注册过滤器,配置属性。

第一种方式

使用步骤:

1.配置字符集过滤器

@Configuration
public class WebSystemConfig {
   //注册Servlet
   @Bean
       public ServletRegistrationBean servletRegistrationBean(){
           MyServlet myServlet = new MyServlet();
           ServletRegistrationBean reg = new ServletRegistrationBean(myServlet,"/myservlet");
           return reg;
      }
       
       
       //注册Filter
       @Bean
   public FilterRegistrationBean filterRegistrationBean(){
       FilterRegistrationBean reg = new FilterRegistrationBean();

       //过滤器类
           CharacterEncodingFilter filter = new CharacterEncodingFilter();
           //指定字符集编码
           filter.setEncoding("utf-8");
           filter.setForceEncoding(true);
           reg.setFilter(filter);

           //指定过滤url
           reg.addUrlPatterns("/*");
           return reg;
      }
}

2.修改application.properties文件,让自定义的过滤器起作用

#在SpringBoot默认已经配置了CharacterEncodingFilter. 编码默认ISO-8859-1
#设置Encoding = false; 作用:关闭系统配置好的过滤器,使用自定义的CharacterEncodingFilter
server.servlet.encoding.enabled=false

第二种方式

修改application.properties文件

server.port=9001
server.servlet.context-path=/myboot
#让系统的CharacterEncdoingFilter生效
server.servlet.encoding.enabled=true
#指定使用的编码的方式
server.servlet.encoding.charset=utf-8
#强制request,response都使用charset属性的值
server.servlet.encoding.force=true

第四章 ORM操作MySQL

使用MyBatis框架操作数据,在SpringBoot框架集成MyBatis

使用步骤:

1.Mybatis起步依赖:完成mybatis对象自动配置,对象放在容器中

2.pom.xml指定src/main/java目录中的xml文件包含到classpath中

3.创建实体类Student

4.创建Dao接口StudentMapper,创建一个查询学生的方法

5.创建Dao接口对应1的Mapper文件,xml文件,写SQL语句

6.创建Service层对象,创建StudentService接口和他的实现类。去dao对象的方法。完成数据库的操作

7.创建Controller对象,访问Service

8.写applicaiton.properties文件配置数据库连接信息

 

第一种方法:@Mapper

@Mapper放在dao接口上面,每个接口都需要这个注解

/**
 * @Mapper:告诉Mybatis这是dao接口,创建此接口的代理对象
 * 位置:在类的上面
 */

@Mapper
public interface StudentMapper {
    Student SelectAllStudent(@Param("stuId") Integer id);
}

 

第二种方式:@MapperScan

@SpringBootApplication
@MapperScan("com.demo04.mapper")
public class SpringBootDemo04MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo04MybatisApplication.class, args);
    }

}

 

 

第三种方式:Mapper文化和dao接口分开处理

现在把Mapper文件放在resources目录下

1.在resources目录中创建子目录(自定义),例如Mapper

2.把,mapper文件放到Mapper目录中

3.在applicaiton.properties文件中,指定mapper文件的目录位置

#整合mybatis
mybatis.type-aliases-package=com.demo04.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

4.在pom.xml指定,把resources目录中的文件,都编译到目标目录中

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

 

第四章事务

Spring框架中的事务:

1.管理事务对象:事务管理器(接口,接口有很多实现类)

例如:使用:JDBC或mybatis访问数据库,使用事务管理器:DataSourceTransactionManager

2.声明式事务:在xml配置文件或者使用注解说明事务控制的内容

控制事务:隔离级别,传播行为,超时时间

3.事务处理方式:

1.spring框架中的Trasactional

2.asoectj框架可以在xml配置文件中,声明事务控制内容

 

SpringBoot中使用事务:上面两种方式都可以

1.在业务方法的上面加入@Transactional,加入注解后,方法有事务功能了

2.明确的在主启动类的上面,加入@EnableTransatctionManager

例子:

@Service
public class StudentServiceImpl  implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    /**
     * Transactional:表示方法有事务的支持
     *  默认:使用的隔离级别,REQUIRED 传播行为:超时时间 -1
     *  抛出运行时异常,回滚事务
     *  没有异常:提交事务
     * @param student
     * @return
     */
    @Transactional
    @Override
    public int addStudent(Student student) {
        System.out.println("Service层");
        int i = studentMapper.insert(student);
        //抛出一个运行时的异常目录回滚事务
//        int m =  10 / 0;



        return i;
    }
}

第五章REST风格

接口:用程序接口英语Application Programming Interface,简称:API),又称为应用编程接口API之主要目的是提供应用程序与开发人员以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。提供API所定义的功能的软件称作此API的实现。API是一种接口,故而是一种抽象

 

接口:可以访问Servlet,Controller的url,调用其他程序函数

架构风格:api组织样式

传统:

https://baike.baidu.com/item/%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E7%BC%96%E7%A8%8B%E6%8E%A5%E5%8F%A3/3350958?fromtitle=API&fromid=10154&fr=aladdin

在地址上提供了访问的资源名称addStudent,在期后使用了get方法传递参数

 

 

RESTful架构风格

1.REST(中文:表现层转移)

REST:是一种接口的架构风格和设计理念,不是标准

优点:更简洁,更有层次

2.REST中的要素:

 

 

第六章 Redis

Redis:一个NoSQL数据库,常用作缓存使用(cache)

Redis的数据类型:string , hash, set,zset,list

 

Redis是一个中间件:它是一个独立的服务器

java中比较著名的客户端:Jedis, lettuce,Redisson

Spring,SpringBoot中有一个 RedisTemplate,(SpringRedisTemplate)处理与redis交互

 

RedisTemplate使用lettuce客户端库

<!--redis起步依赖,直接可以在项目中使用(RedisTemporal)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    data-redis使用的lettuce客户端库
    
    在程序中要用RedisTemplate类的方法操作redis数据,实际就是调用lettuce客户端中的方法

6.1对比redisTemplate和stringRedisTemplate

stringRedisTemplate:把k,v都是作为String处理,使用的是String的系列化,可读性好

redisTemplate:把k,v经过了序列化存到redis.kv都是序列化

image-20220328200147182

设置key或者value的序列化

@PostMapping("/redis/addstr")
public String addString(String k, String v) {
    //使用RedisTemplate
    //设置的k 使用string的序列化
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    //设置value的序列化
    redisTemplate.setValueSerializer(new StringRedisSerializer());
    redisTemplate.opsForValue().set(k,v);
    return "定义RedisTemplate对象的key,value的序列化";

 

第七章SpringBoot集成Dubbo

7.1看springboot集成dubbo

 

 

第八章SpringBoot打包

 

 

第九章模板引擎

Thymeleaf:是使用java开发的模板技术,在服务器端运行.把

posted @   东渡素玄  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示