SpringBoot笔记

SpringBoot

依赖管理
  • parent方式
  • dependencyManagement方式
    <dependencyManagement></dependencyManagement>
主要注解@SpringBootApplication
  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan
启动方式

1.静态方式启动
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
2.动态方式
SpringApplication application = new SpringApplication();
Set<String> sets = new LinkedHashSet<>();
sets.add(DemoApplication.class.getName());
application.setSources(sets);
ConfigurableApplicationContext run = application.run(args);

配置分析

一、获取配置信息的方式

方式1

ConfigurableApplicationContext run = application.run(args);
String property = run.getEnvironment().getProperty("local.ip");

方式2

@Value("${local.port}")

方式3

@Autowired private Environment env;

二、配置文件
1.默认的位置在classpath根目录,或者classpath:/config,file:/,file:config/
2.默认的配置文件名字可以使用–spring.config.name来指定,只需要指定文件的名字,文件扩展名可以省略。
3.默认的配置文件路径可以使用–spring.config.location来指定,配置文件需要指定全路径,包括目录和文件名字,还可以指定多个,多个用逗号隔开
文件的指定方式有两种,1:classpath:2:file
4.@PropertySource(“classpath:jdbc.properties”)
@PropertySource(“file:/e:/tmp/jdbc.properties”)
@PropertySources({@PropertySource(“classpath:jdbc,properties”),@PropertySource(“file:/e:/tmp/jdbc.properties”)})
5.@ConfigurationProperties(prefix=“ds”)
6.@ConfigurationProperties(prefix=“ds”,locations=“classpath:ds.properties”)
7.@ConfigurationProperties(locations=“classpath:ds.properties”)
8.@Profile()

SpringBoot自动配置

public interface Condition{ boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata); }
@Conditional(UTF8Condition.class)
可以用在类上对所有方法有效,可以用在方法上,对指定方法有效
SpringBoot提供了大量条件注解方便用户使用

SpringBoot @Enable*注解的工作原理

@EnableConfigurationProperties:可以把配置文件里的属性注入到Bean里面去,一般和@ConfigurationProperties一起使用
@EnableAsync启用异步 一般和@Async一起使用
@Import:用来导入一个或多个类(会被spring容器托管),或者配置类(配置类里的所有Bean都会被容器托管)
ImportSelector接口的selectImports方法的返回值必须是一个class(全称),该class会被spring容器所管理,可以获取到注解的详情信息,然后根据详情信息去动态的返回需要被spring容器管理的bean
ImportBeanDefinitionRegistrar:用来向spring容器中注册Bean

@EnableAutoConfiguration:从classpath中搜索所有META-INF/spring.factories配置文件,得到所有以
org.springframework.boot.autoconfigure.EnableAutoConfiguration为键的对应的值(com.example.demo.test1.RunnableConfiguration),然后去重并排除掉被指定的bean,以数组的形式返回,加载到spring容器中。
只有spring.boot.enableautoconfiguration为 true(默认为true)的时候,才启用自动配置

事件流程

1:自定义事件,一般是继承ApplicationEvent抽象类
2:定义事件监视器,一般是实现ApplicationListener接口
3:发布事件
配置监听器有多种方法:1.app.addListeners();
2加入到容器中去。
3.context.listener.classes=xxx 配置项.
4.@EventListener注解,加在方法上,类要加载到容器中

SpringBoot扩展

1.ApplicationContextInitializer
ApplicationContextInitializer接口是在容器执行refreshed()之前的一个回调
使用步骤:
1.写一个类实现ApplicationContextInitializer接口
2.注册ApplicationContextInitializer
注册方法:
1.使用SpringApplication.addInitializers()
2.在配置里配置,context.initializer.classes指定,可以指定多个,多个用逗号隔开
3.可以通过spring.factories机制(注册listener监听器也可以使用这种方式)
2.CommandLineRunner
CommandLineRunner接口是在容器启动成功后的最后一步回调
使用步骤:
1.写一个类实现CommandLineRunner接口
2.把该类加入到容器中
注意:有多个时,可以通过@Order注解或者Ordered接口来控制执行顺序。
ApplicationRunner:区别为参数不一样,CommandLineRunner的参数为原始参数,没有做任何处理,
ApplicationRunner的参数为ApplicationArguments,对原始参数进行了封装。
ApplicationArguments是对参数(main方法)做个进一步的处理,可以解析–name=value的,我们就可以通过name来获取value了,不然的话得到的是一个原始字符串,需要自己分隔处理。

Spring Boot运行流程分析
  1. 直接调用静态的run方法(内部转换成第二种方式)
    ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
  2. 实例化SpringApplication对象,然后调用run方法
    运行流程:
    1.判断是否是web环境
    2.加载所有classpath下面的META-INF/spring.factories ApplicationContextInitializer
    3.加载所有classpath下面的META-INF/spring.factories AppliationListener
    4.推断main方法所在的类。
    5.开始执行run方法
    6.设置java.awt.headless系统变量
    7.加载所有classpath下面的META-INF/spring.factories SpringApplicationRunListener
    8.执行所有SpringApplicationRunListener的started方法
    9.实例化ApplicationArgumens对象(根据main方法的args)
    10.创建environment
    11.配置environment,主要是把run方法的参数配置到environment
    12.执行所有SpringApplciationRunListener的environmentPrepared方法
    13.如果不是web环境,但是是web的environment,就转换成标准的environment
    14.打印Banner
    15.初始化applicationContext,如果是web环境创建
    org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
    如果不是web环境创建
    org.springframework.context.annotation.AnnotationConfigApplicationContext
    16.如果beanNameGenerator不为空,就把beanNameGenerator对象注入到context里面去
    17.回调所有的ApplicationContextInitializer方法
    18.执行所有SpringApplicationRunListener的contextPrepared方法
    19.依次往spring容器中注入ApplicationArguments,Banner
    20.加载所有的源到context里面去
    21.执行所有SpringApplicationRunListener的contextLoaded方法
    22.执行context的refresh()方法,并且调用context的registerShutdownHood方法
    23.回调,获取容器中所有的ApplicationRunner、CommandLineRunner接口,然后排序依次调用。
    24.执行所有SpringApplicationRunListener的finished方法
SpringBoot Web

@GetMapping @PostMapping:spring4.3 新特性 ,请求方法
@RequestParam:绑定请求中的参数
@PathVariable:绑定url路径中的参数

拦截器的使用步骤:
1.写一个拦截器,实现HandlerInterceptor接口
2.写一个类,集成WebMvcConfigurerAdapter抽象类,然后重写addInterceptors方法,并调用registry.addInterceptor把上一步的拦截器加进去。
HandlerInterceptor
preHandle:controller执行之前调用
postHandle:controller执行之后,且页面渲染之前调用
afterCompletion:页面渲染之后调用,一般用于资源清理操作

异常处理
如何去掉spring boot默认的异常处理逻辑
@SpringBootApplication(exclude=ErrorMvcAutoConfiguration.class)
使用ErrorPageRegisterar方法
写一个类,实现ErrorPageRegistrar接口,然后实现registerErrorPages方法,在该方法里面,添加具体的错误处理逻辑。(类似web.xml里面配置错误处理方法)

全局异常处理步骤
1.写一个类,需要加上@ControllerAdvice注解
2.写一个异常处理方法,需要加上@ExceptionHandler(value=Exception)这个注解,在该方法内处理异常。

SpringBoot定制和优化内嵌的Tomcat

两种定义tomcat容器的方法
1.实现EmbeddedServletContainerCustomizer接口,并把实现纳入到spring容器中管理
2.在spring容器中装配TomcatEmbeddedServletContainerFactory。

数据源

装配DataSource的步骤
1.加入数据库驱动
2.装配
spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
以上操作,springboot会自动装配好DataSource、JdbcTemplate,可以直接使用
spring.datasource.type可以指定具体使用哪种数据源
默认支持tomcat-jdbc、Hikari、dbcp、dbcp2

自己配数据源
只需要装配一个DataSource到spring容器中即可

事务
1.@Enablexxx启动事务
2.@Transactional 默认只会对运行时异常进行事务回滚,非运行时异常不会回滚事务
@Transactional(rollbackFor=Exception.class)设置对那些异常进行回滚
(noRollbackFor=) 设置那些不回滚
直接调用的方法必须有注解才会生效。

Spring Boot Aop

AOP开发流程
1.spring-boot-starter-aop,加入依赖,默认就开启了AOP的支持
2.写一个Aspect,封装横切关注点(日志,监控等等),需要配置通知(前置通知、后置通知等等)和切入点(那些包的那些类的那些方法等等)
3.这个Aspect需要纳入到spring容器中管理,并且需要加上@Aspect注解

spring.aop.auto配置项决定是否启用AOP,默认启用
默认是使用基于JDK的动态代理来实现AOP
spring.aop.proxy-target-class=false 或者不配置,表示使用JDK的动态代理
=true,表示使用cglib
如果配置了false,而类没有接口,则依然使用cglib

SpringBoot starter 开发步骤

1.新建一个项目
2.需要一个配置类,配置类里面需要装配好需要提供出去的类
3.(1)使用@Enablexxx,使用@Import注解导入需要装配的类
(2)/META-INF/spring.factories,在org.springframework.boot.autoconfigure.EnableAutoConfiguration配置需要装配的类

Spring Boot 日志

SpringBoot默认的日志级别是info
可以通过logging.level.* = debug 来设置,*可以是包,也可以是某个类
日志级别有:TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF
logging.file=d:/tmp/my.log 指定日志文件名字
logging.path=d:/tmp/logs 指定路径,默认名字为spring.log
日志文件输出,文件的大小10M之后,就会分割了
logging.pattern.console=%-20(%d{yyyy-MM-dd HH:mm:ss.SSS}[%hread])%logger{80}-%msg%n 配置控制台输出日志的pattern
logging.file.console= 配置日志文件输出日志的pattern

logback.xml 或 logback-spring.xml也可以定制日志输出,springBoot默认支持log back,放到classpath下即可。

使用其他的日志组件步骤:
1.排除掉默认的日志组件:spring-boot-starter-logging
2.加入新的日志路径依赖
3.把相应的配置文件放到classpath下

Actuaoar

自定义健康状态监测,实现HealthIndicator接口,并纳入到spring容器的管理之中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值