SpringBoot学习总结

本文详细介绍了SpringBoot的学习过程,包括创建第一个SpringBoot项目、端口配置、自动装配原理、yaml语法详解、JSR303数据校验、JDBC、Druid、Mybatis的整合、SpringSecurity的配置与权限控制、Shiro的环境搭建与功能实现、Swagger的集成与API管理、异步任务、定时任务和邮件任务的处理,以及Dubbo与Zookeeper的整合。通过这篇博客,读者将全面掌握SpringBoot的核心技术和实践应用。
摘要由CSDN通过智能技术生成

目录

1、我的第一个SpringBoot项目

创建SpringBoot项目

如何修改端口号

2、SpringBoot自动装配原理

3、yaml语法

用yaml赋值

配置文件占位符 

结论:

4、JSR303数据校验及多环境切换

5、整合JDBC,Druid,Mybatis

1.整合JDBC

2.整合Druid

3.整合Mybatis

6、SpringSecurity

实验环境搭建

认识SpringSecurity

认证和授权

1.引入 Spring Security 模块

2.编写 Spring Security 配置类

权限控制和注销

1.开启自动配置的注销的功能

2.在前端中添加一个注销按钮 

3.其他功能实现

记住我

定制登录页

7、Shiro

1.springboot整合shiro环境搭建

2.shiro实现登录拦截

3.Shiro实现用户认证 

4.Shiro整合Mybatis

5.Shiro请求授权实现

6.Shiro整合thymeleaf

8、Swagger

1.SpringBoot集成Swagger

2.配置Swagger

3.配置扫描接口

4.配置Swagger开关

5.配置API分组

6.实体配置

7.常用注解

9、异步、定时、邮件任务

1.异步任务

2.定时任务

3.邮件任务

10、Dubbo&Zookeeper

1.Dubbo

2.Dubbo+Zookeeper环境搭建

Zookeeper

Dubbo

3.SpringBoot+Dubbo+Zookeeper

服务提供者

服务消费者

启动测试


1、我的第一个SpringBoot项目

创建SpringBoot项目

 

选择导入的依赖,完成即可构建成功! 

测试一下

 启动springboot

 

成功访问 

如何修改端口号

修改后重启

 8080无响应

8081可以访问

2、SpringBoot自动装配原理

3、yaml语法

用key:空格 value表示

用yaml赋值

 实体类。使用@ConfigurationProperties注解要导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

 

yaml文件中进行对实体类的赋值,birth一定要注意格式

 测试类和测试结果

 property赋值

 测试结果

配置文件占位符 

配置文件还可以编写占位符生成随机数

对比:

@Value这个使用起来并不友好,我们需要为每个属性单独注解赋值,比较麻烦;我们来看个功能对比图 

1、@ConfigurationProperties只需要写一次即可 , @Value则需要每个字段都添加

2、松散绑定:这个什么意思呢? 比如我的yml中写的last-name,这个和lastName是一样的, - 后面跟着的字母默认是大写的。这就是松散绑定。可以测试一下

3、JSR303数据校验 , 这个就是我们可以在字段是增加一层过滤器验证 , 可以保证数据的合法性

4、复杂类型封装,yml中可以封装对象 , 使用value就不支持

结论:

配置yml和配置properties都可以获取到值 , 强烈推荐 yml;

如果我们在某个业务中,只需要获取配置文件中的某个值,可以使用一下 @value;

如果说,我们专门编写了一个JavaBean来和配置文件进行一一映射,就直接@configurationProperties,不要犹豫!

4、JSR303数据校验及多环境切换

Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。我们这里来写个注解让我们的name只能支持Email格式;

运行会直接报错

使用数据校验,可以保证数据的正确性;

@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;

空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
    
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) string is between min and max included.

日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

.......等等
除此以外,我们还可以自定义一些数据校验规则

5、整合JDBC,Druid,Mybatis

1、整合JDBC

application.yml文件中配置JDBC

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

2、整合Druid

导入依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

Druid数据源的yml配置

    #SpringBoot默认是不注入这些的,需要自己绑定
    #druid数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
    #则导入log4j 依赖就行
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

设置一个后台监控

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    //后台监控 : web,xml, ServletRegistrationBean
    //因为SpringBoot内置了servlet容器,所以没有web.xml,替代方法 ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        //后台需要有人登录,账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();

        //增加配置
        initParameters.put("loginUsername","admin");//登录key 是固定的  loginUsername loginPassword
        initParameters.put("loginPassword","123456");

        //允许谁可以访问
        initParameters.put("allow","");//参数为空,所有人都可以访问

        //禁止谁能访问    initParameters.put("lqh","192.168.1.1");

        bean.setInitParameters(initParameters);//设置初始化参数
        
        return bean;
    }
}

登录访问localhost:8080/druid

 设置一个简单的过滤器

    //filter过滤器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        //可以过滤哪些请求
        Map<String,String> initParameters = new HashMap<>();
        //这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);

        return bean;
    }

3、整合Mybatis

实体类

 mapper接口

在resources下新建mybatis/mapper/UserMapper.xml 来存放xml文件

application.properties配置mybatis的配置信息

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

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

 Controller层

6、SpringSecurity

实验环境搭建

1、新建一个初始的springboot项目web模块,thymeleaf模块

2、导入静态资源

3、controller跳转

认识SpringSecurity

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

认证和授权

目前,我们的测试环境,是谁都可以访问的,我们使用 Spring Security 增加上认证和授权的功能

1、引入 Spring Security 模块

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

2、编写 Spring Security 配置类

@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页面只有对应有权限的人才能访问
        //权限授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("vip1")
                                .antMatchers("/level2/**").hasRole("vip2")
                                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限会默认到登录页面
        http.formLogin();
    }

    //认证

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以在jdbc中去拿
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
        //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("liuqianhao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("liangzhu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
    }
}

权限控制和注销

1、开启自动配置的注销的功能

2、在前端中添加一个注销按钮 

                <a class="item" th:href&#
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值