spring-boot 笔记

用户头像
solike
关注
发布于: 2020 年 10 月 18 日

Spring-boot作为目前spring应用的快速开发模式,无论是普通的单体web应用,还是大型的基于spring cloud的分布式微服务项目,都有它的用武之地。相比传统的开发模式具备以下优势:

1.编码及配置层面,借助spring4注解配置的支持,定义了一系列特定依赖的自动化配置,应用只需引入相关的starter依赖就实现了bean的注册,在默认配置下也可自定义,这种开箱即用的特性避免了繁琐的xml配置,通过starter初始化向导快速生成依赖的pom配置文件也简化了项目的搭建。

2.部署及生产特性,spring-boot应用打包后可独立运行(内嵌容器),只需要具备java环境,同时也可发布到web容器中运行,通过actuater度量监控暴露http端点,也可通过其他协议往外暴露度量数据,方便对应用进行调试及应用状态监控。

Spring入门:

IOC容器装载(注册)Bean方式:

@Configuration(添加在配置类)

配置类中在方法上添加@Bean配置bean(可定义Bean初始化和销毁方法,1.指定方法名,2实现初始化及销毁接口,3.@PostContuct,@PreDestory)

1. @Bean注解

2. FactoryBean<T>针对复杂初始化bean情况,并通过@Bean注册相应bean,FactoryBean通过&beanName获取。

3. @Component,@Repository,@Service,@Controller,@RestController等

注入Bean方式:

@Autowired,@Qualifier,@Resource,@Inject

Spring扩展分析:

1. BeanPostProcessor (bean后置处理器)用于bean实例化之后,初始化方法之前或之后做特殊处理。

2. BeanFactoryPostProcessor对BeanFactory处理。

 

spring-boot入门:

@SpringBootApplication

(包括@SpringBootConfiguration,@ComponentScan,@EnableAutoConfiguration)

public class App{

public static void main(String [] args) {

SpringApplication.run(App.class,args);

}

}

获取配置:

Environment获取配置

@Value

@PropertySources

@ConfigurationProperties

加载外部化配置:注册EnvironmentPostProcessor.

配置环境: @Profile

spring.profile.active

application-dev.yml,application-test.properties

 

自动化配置分析:

1. Condition接口定义了match方法,参数为ConditionContext接口,该参数提供了获取BeanDefinitionRegistry对象,ConfigurableListableBeanFactory对象,Environment对象,以及AnnotatedTypeMetadata参数,通过实现match方法,返回true表示Condition条件满足,对bean进行注册。再结合@Conditional注解及相应的Condition类进行灵活的条件装配,spring-boot-starter-autoconfigure中定义了大量相关的类及注解,常见的注解有@ConditionOnClass,@ConditionOnBean,@ConditionOnProperty等,这种条件化的装配是实现自动化配置的关键。

2. @Enable*注解:(都包含一个@Import注解,注解属性是一个Class对象,用于定义那些配置类(方法用于bean注册)应该生效,或者ImportSelector Class对象定义多个配置类生效,通过实现String[] selectImports(AnnotationMetadata var1)方法,返回Class类名数组表示对应的配置类生效,或者ImportBeanDefinitionRegistrar Class对象,通过实现registerBeanDefinitions方法,对指定bean进行注册)

3. @EnableAutoConfiguration注解使用的是AutoConfigurationImportSelector,其中的selectImports方法会读取类路径META-INF/spring.factories中的配置类并进行生效。

Spring事件监听:

1. 定义事件类继承ApplicationEvent类

2. 定义事件监听器类实现ApplicationListener接口,并进行注册,或者在注册的监听类的监听方法上使用@EventListener注解。

3. ApplicationContext中发布事件。

spring-boot扩展:

1. ApplicationContextInitializer

2. ComandLineRunner

3. ApplicationRunner

spring-boot-start-web:

常用注解有:@RestController,@RequestMapping (@PostMapping等),@RequestParam,@RequestBody,@RequestHeader

内嵌tomcat容器,也可配置其他容器,比如jetty,undertow容器.



发布于: 2020 年 10 月 18 日 阅读数: 14
用户头像

solike

关注

还未添加个人签名 2020.02.17 加入

还未添加个人简介

评论

发布
暂无评论
spring-boot笔记