SpingBoot的使用

SpingBoot常用注解

  1. @Configuration

    相当于spring 里的一个xml配置文件, beans.xml

  2. @Bean

    作用于方法上, 相当于xml 配置中的

    当Bean 标签修饰的方法有形式参数时, 那么形式参数的值会默认加上@Autowired 也就是会从IOC 容器里取值

  3. @Import

    在创建配置文件之后可以引入其他配置文件

  4. @Qualifier

    意思是合格者, 通过注解表明哪个实现类才是我们所需要的, 我们修改调用代码, 添加@Qualifier注解, 需要注意的是@Qualifier的参数名称必须为我们之前定义的@Bean注解的名称之一

SpringBoot启动分析

Application.java
  • @SpringBootApplication 就是对spring Configuration的包装

  • @EnableAutoConfiguration 自动扫描包的配置, 默认为当前启动类所在的包及子包

    springboot会默认加载很多配置文件, 项目启动后, 没有用到的配置文件会被自动删除

SpringBoot热部署

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    	</dependency>
    

SpringBoot的两种配置文件

  • Spring Configuration Processor 自动提示配置

    添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <scope>annotationProcessor</scope>
    	</dependency>
    
  • application.yml

  • application.properties

    • 两种方法的说明
      • 在同一个目录下如果properties里面配置了就不会去yml里取值, 如果没有配置就会去yml里取值
      • 两种配置方法是互补的
  • @ConfigurationProperties(prefix=“student”)读取配置文件

  • @Validated验证处理

    • @ConfigurationProperties(prefix=“student”)下可以添加@Validated标签支持验证功能, 再在属性字段上添加验证类型标签, 例如@Email
  • @Value读取配置文件

  • 区别

    • @Value只能注入普通的属性, 基本数据类型和Date

    • 如果属性使用驼峰命名则不能使用属性名注入, 要使用@Value("${student.user-name}")来取值

    • @ConfigurationProperties(prefix=“student”)和@Value最大的区别是@Value是主动去IOC容器里取值, @ConfigurationProperties(prefix=“student”)是被动的去接收IOC容器里注入的值

      @ConfigurationProperties@Value
      功能批量注入配置文件中的属性一个个指定
      松散绑定支持不支持
      SpEL不支持支持
      JSR303数据校验支持不支持
      复杂类型封装(对象)支持不支持

@PropertySource和ImportResource

可以导入其他名称的配置文件

Profiles配置

  • 生产环境

  • 开发环境

  • 测试环境

  • 指定配置文件版本

    spring:

    ​ profiles:

    ​ active: dev

  • 对象添加@Profile注解可以指定版本

配置文件加载优先级

  • file: ./config/ 当前项目路径config目录下

  • file: ./ 当前项目路径下

  • classpath: ./config/ 类路径config目录下

  • classpath: ./ 类路径下

  • 配置外部配置文件

    java -jar 项目名称 --spring.config.location=外部配置文件路径

  • 配置配置文件版本

    java -jar 项目名称 --spring.profiles.active=pro

  • 配置端口号

    java -jar 项目名称 --server.port=8080

自动配置原理和@Conditional派生注解相关属性

  • @JsonFormat 解析后端日期格式
  • @DateTimeFormat 解析前端日期格式
  • @Conditional 必须指定的条件成立,才给容器中添加组件,配置类里的所有内容才会生效
    • @ConditionalOnClass
    • @ConditionalOnBean
    • @ConditionalOnWebApplication

静态资源访问规则

  • 以下目录的资源文件可以通过url直接访问,且src/main/resources/META-INF/resources目录下优先级最高

  • src/main/resources/META-INF/resources/

  • src/main/resources/resources/

  • src/main/resources/static/

  • src/main/resources/public/

AOP开发

添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • @Before @After @Around

Thymeleaf模板的使用

  • 完全可以替代jsp, 存放于 /template/ 目录下

  • 添加依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • 使用

    • 语法
      • 变量表达式: ${ }
      • 信息表达式: #{ }
      • 链接URL表达式: @{ }
    • 字面值
      • 文本文字
      • 文字数量
      • 布尔型常量
      • 空的文字
      • 文字标记
    • 文本处理
      • 字符串并置
      • 文字替换
    • 表达式基本对象
      • #ctx: 上下文对象
      • #vars: 上下文变量
      • #locale: 上下文语言环境
      • #httpServletRequest: HttpServletRequest对象
      • #httpSession: HttpSession对象
    • 实用工具对象
      • #dates: 日期格式,组件提取
      • #numbers: 格式化数组对象的实用方法
      • #strings: 字符串对象的实用方法,包含startsWith,将/附加等
      • #objects: 实用方法的对象
      • #bools: 布尔评价的实用方法
      • #arrays: 数组的实用方法
      • #lists: list集合
      • #sets: set集合
      • #maps: map集合
      • #aggregates: 实用程序方法用于创建聚集在数组或集合
      • #messages: 实用程序方法获取外部信息内部变量表达式,以同样的方式,因为他们将获得使用#{ }语法
      • #ids: 实用程序方法来处理可能重复的id属性
  • 国际化

    • 创建信息源文件
      • student_zh_CN.properties
      • student.properties
    • 读取信息源
      • #{ }
  • Thymeleaf读取Model里的对象

    • ${ }
  • Thymeleaf读取Model里的集合

    • th:each=“student:${students}”
  • Thymeleaf在js中取值

    • [[${student.id}]] 取数字
    • ‘[[${student.name}]]’ 取字符串
  • Thymeleaf链接传值

    • <a th:href="@{user/queryAllUser.action?username=admin&password=123456}">登录</a>
    • <a th:href="@{user/queryAllUser.action(username=admin,password=123456)}">登录</a>
  • Thymeleaf占位符

    • <div th:text="#{welcome(‘小明’,‘上学’))}"><div>
  • Thymeleaf中的Objects

    • ${ }读取model里的数据,没有就会去request对象里找
    • ${#httpSession.getAttribute(‘name’)} 取session里的数据
    • ${#servletContext.getAttribute(‘name’)} 取context里的数据

管理及扩展springmvc组件

  • application.yml

    mvc

    ​ date-fomat: yyyy-MM-dd #当前端提交字符串日期到后台时进行格式化

    ​ view:

    ​ prefix: /WEB-INF/view

    ​ suffix: .jsp

    jackson

    ​ date-format: yyyy-MM-dd #当后端转化json串到前端时对日期进行格式化

    ​ time-zone: GMT+8

  • 控制器的自动管理

  • 视图解析器的自动管理

    • ViewResolver
  • 配置springboot支持jsp

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifacId>spring-boot-starter-tomcat</artifactId>
    	<scope>provided</scope>
    </dependency>
    <dependency>
    	<groupId>org.apache.tomcat.embed</groupId>
    	<artifacId>tomcat-embed-jasper</artifactId>
    	<scope>provided</scope>
    </dependency>
    <dependency>
    	<groupId>org.eclipse.jdt.core.compiler</groupId>
    	<artifacId>ecj</artifactId>
      <version>4.6.1</version>
    	<scope>provided</scope>
    </dependency>
    
  • 文件上传

    • MultipartAutoConfiguration

    • application.yml

      #文件上传配置

      servlet:

      ​ multipart:

      ​ enabled: true

      ​ location: /Users/wushang/Desktop/upload/

      ​ max-file-size: 10MB

      ​ max-request-size: 5MB

  • 静态资源访问

  • 消息转化和格式化

    • Converter 类型转换器
  • 欢迎页面自动配置

  • 在容器中注册视图控制器

  • 注册格式化

  • 消息转化器扩展 fastjson

  • 注册拦截器

    • @ConfigurationProperties(prefix=“spring.mvc.inteceptor”)
    • MyHandlerInterceptor

内嵌服务器加载原理

  • ServletWebServerFactoryAutoConfiguration 配置类

注册WEB三大组件

  • 三大组件
    • Servlet
      • @WebServlet("/user.action")
    • WebFilter
      • @Filter
    • Listener
      • @WebListener
      • Request
        • ServletRequestListener
        • ServletRequestAttributeListener
      • Session
        • HttpSessionListener
        • HttpSessionAttributeListener
      • ServletContext
        • ServletContextListener
        • ServletContextAttributeListener

集成外部Tomcat

  • 外部的Tomcat只支持war包

数据源的配置和自动管理

  • DataSourceAutoConfiguration

  • application.yml 配置数据源参数

    • 默认使用Hikari 数据源

      spring:

      ​ datasource:

      ​ driver-class-name:

      ​ url:

      ​ username:

      ​ password:

      ​ type: 数据源

      DBCP2
      type: org.apache.commons.dbcp2.BasicDataSource
      <dependency>
      	<groupId>org.apache.commons</groupId>
      	<artifactId>commons-dbcp2</artifactId>
      </dependency>
      
      DRUID
      type: com.alibaba.druid.pool.DruidDataSource
      <dependency>
      	<groupId>com.alibaba</groupId>
      	<artifactId>druid</artifactId>
      </dependency>
      
  • druid监控页面配置

    • 只需要引入starter依赖,修改application.yml

      spring:

      ​ datasource:

      ​ druid:

      ​ driver-class-name:

      ​ url:

      ​ username:

      ​ password:

      ​ max-active:

      ​ max-wait:

      ​ initial-size:

      ​ filters: stat,log4j,wall

      ​ enable: true

      ​ validationQuery: SELECT ‘X’

      ​ stat-view-servlet:

      ​ enabled: true

      ​ login-username: root

      ​ login-password: 123456

      ​ allow:

      ​ deny:

      ​ url-pattern: /druid/*

      ​ web-stat-filter:

      ​ enabled: true

      ​ exclusions: “.js,.gif,.jpg,.png,.css,.ico,/druid/*”

集成JDBCTemplate

  • springboot只需要配置数据源就可以使用

整合MyBatis及事务处理

  • 使用注解方式完成整合

    • 添加依赖 MyBatis Framework

      <dependency>
      	<groupId>org.nybatis.spring.boot</groupId>
      	<artifactId>mybatis-spring-boot-starter</artifactId>
      	<version>2.1.0</version>
      </dependency>
      
    • 在*Mapper接口上添加@Mapper注解或在启动类添加@MapperScan注解

  • 使用xml方式完成整合

    在*Mapper接口上添加@Mapper注解或在启动类添加@MapperScan注解

    mybatis:

    ​ configuration:

    ​ log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

    ​ mapper-locations:

    ​ - classpath: mapper/*Mapper.xml

  • 分页插件PageHelper的使用

    • 使用原生PageHelper

      • 引入依赖

        <dependency>
        	<groupId>com.github.pagehelper</groupId>
        	<artifactId>pagehelper</artifactId>
        	<version>5.1.10</version>
        </dependency>
        
      • 在mybatis.cfg.xml中引入pagehelper插件,或者创建pagehelper配置类并在yml中配置

    • 使用pagehelper-starter

      • 直接引入依赖

        <dependency>
        	<groupId>com.github.pagehelper</groupId>
        	<artifactId>pagehelper-spring-boot-starter</artifactId>
        	<version>1.2.12</version>
        </dependency>
        
  • 在项目中一般使用Mybatis的xml + pagehelper-starter

    • pom.xml

      <dependency>
      	<groupId>org.nybatis.spring.boot</groupId>
      	<artifactId>mybatis-spring-boot-starter</artifactId>
      	<version>2.1.0</version>
      </dependency>
      <dependency>
      	<groupId>com.github.pagehelper</groupId>
      	<artifactId>pagehelper-spring-boot-starter</artifactId>
      	<version>1.2.12</version>
      </dependency>
      
    • application.yml

      mybatis:

      ​ configuration:

      ​ log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

      ​ mapper-locations:

      ​ - classpath: mapper/*Mapper.xml

  • 事务管理

    • @Transactional注解加在类上,代表类里的所有方法要加入事务管理
    • @Transactional(readOnly=true) 不使用事务

SpringBoot集成swagger

  • 添加依赖

    <dependency>
    	<groupId>io.springfox</groupId>
    	<artifactId>springfox-swagger2</artifactId>
    	<version>2.9.2</version>
    </dependency>
    <dependency>
    	<groupId>io.springfox</groupId>
    	<artifactId>springfox-swagger-ui</artifactId>
    	<version>2.9.2</version>
    </dependency>
    
  • 创建Swagger配置类

    @Configuration
    @EnableSwagger2
    public class Swagger2AutoConfiguration{
    	//在IOC容器里创建对象可以监控Controller里的注解是否有Swagger相关注解,若有,会生成相关文档
    	@Bean
    	public Docket swaggerSpringMvcPlugin(){
    		return new Docket(DocumentationType.SWAGGER_2).select()
    		.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    	}
    }
    
  • @Api(value=“用户管理”,consumes=“用户管理”,tags={“用户管理”},description=“描述”)

  • @ApiOperation(value=“方法描述”)

  • 必填属性

    • @ApiImplicitParams({

      ​ @ApiImplicitParam(name="",value="",required=true)

      })

  • swagger更换UI

    • 添加依赖
    <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>
    
    • 更改配置类
    @Configuration
    @EnableSwagger2
    public class Swagger2AutoConfiguration{
    	//在IOC容器里创建对象可以监控Controller里的注解是否有Swagger相关注解,若有,会生成相关文档
    	@Bean
    	public Docket swaggerSpringMvcPlugin(){
    		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
    		.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    	}
    	
    	private ApiInfo apiInfo(){
    		return new ApiInfoBuilder().description("这是一个API工具")
    			.contact(new Contact("","",""))
    			.version("1.0")
    			.license("")
    			.build();
    	}
    }
    

SpingBoot集成Shiro

  • 非前后端分离

    • 添加依赖

      <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-spring</artifactId>
          <version>1.4.1</version>
      </dependency>
      <dependency>
          <groupId>com.github.theborakompanioni</groupId>
          <artifactId>thymeleaf-extras-shiro</artifactId>
          <version>2.0.0</version>
      </dependency>
      
      
    • 页面标签

      <html xmlns:th="http://www.thymeleaf.org"
      			xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
      
      
    • thymeleaf配置

      thymeleaf:
      	cache: false
      	enabled: true
      
      
    • shiro配置类

      @Configuration
      @ConditionalOnWebApplication(type=Type.SERVLET)
      @ConditionalOnClass(value={SecurityManager.class})
      @ConfigurationProperties(prefix="shiro")
      @Data
      public class ShiroAutoConfiguration{
        
        private String hashAlgorithmName = "md5";
        private int hashIterations = 2;
        private String loginUrl="/index.html";
        private String[] anonUrls;
        private String logOutUrl;
        private String[] authcUrls;
        
        //声明凭证匹配器
        @Bean("credentialsMatcher")
        public HashedCredentialsMatcher hashedCredentialsMatcher(){
          HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
          credentialsMatcher.setAlgorithmName(hashAlgorithmName);
          credentialsMatcher.setHashIterations(hashIterations);
          return credentialsMatcher;
        }
        
        //声明Realm
        @Bean("userRealm")
        public UserRealm userRealm(CredentialsMatcher credentialsMatcher){
          UserRealm userRealm = new UserRealm();
          userRealm.setCredentialsMatcher(credentialsMatcher);
          return userRealm;
        }
        
        //声明安全管理器
        @Bean("securityManager")
        public SecurityManager securityManager(UserRealm userRealm){
          DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
          securityManager.setRealm(userRealm);
          return securityManager;
        }
        
        //配置过滤器
        @Bean("shiroFilter")
        public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
          ShiroFilterFactoryBean  factoryBean = new ShiroFilterFactoryBean();
          factoryBean.setLoginUrl(loginUrl);
          Map<String, Object> filterChainDefinitionMap = new HashMap<>();
          if(anonUrls!=null && anonUrls.length>0){
            for(String anon : anonUrls){
              filterChainDefinitionMap.put(anon, "anon");
            }
          }
          if(null!=logOutUrl){
            filterChainDefinitionMap.put(logOutUrl, "logout");
          }
          if(authcUrls!=null && authcUrls.length>0){
            for(String anon : anonUrls){
             filterChainDefinitionMap.put(authc, "authc");
            }
          }
          factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
          return factoryBean;
        }
        
        //注册过滤器
        @Bean
        public FilterRegistrationBean<DelegatingFilterProxy> delegatingFilterProxy(){
          FilterRegistrationBean<DelegatingFilterProxy> filterRegistrationBean = new FilterRegistrationBean<>();
          DelegatingFilterProxy proxy = new DelegatingFilterProxy();
          proxy.setTargetFilterLifecycle(true);
          proxy.setTargetBeanName(SHIRO_FILTER);
          filterRegistrationBean.setFilter(proxy);
          return filterRegistrationBean;
        }
        
        //加入注解使用
        @Bean
        public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
          AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
          authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
          return authorizationAttributeSourceAdvisor;
        }
        @Bean
        public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
          DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
          advisorAutoProxyCreator.setProxyTargetClass(true);
          return advisorAutoProxyCreator;
        }
        
        //配置shiro标签
        @Bean(name = "shiroDialect")
        public ShiroDialect shiroDialect(){
          return new shiroDialect;
        }
      }
      
    • application.yml

      #shiro
      shiro:
      	hash-alogrithm-name: md5
      	hash-iterations: 2
      	anon-urls:
      	- /index.html*
      	- /login/toLogin*
      	- /login/login*
      	login-url: /index.html
      	log-out-url: /login/logout*
      	authc-urls:
      	- /**
      	
      
  • 前后端分离

    • 只返回数据
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值