《Spring官方文档》_笔记

1 Overview

spring官网文档
IOC,三级缓存,循环依赖。
AOP,cglib动态代理;配合IOC,注入动态代理后的实例。

3,Design Philosophy

Provide choice at every level.
Accommodate diverse perspectives.

2 Core Technologies

容器、配置元数据、注册机制、bean;扩展

1,The IOC Container

三级缓存,解决循环依赖。spring循环依赖
构造器注入(验证对象)、属性注入(避免因循环依赖而注入失败)。
Context层级:

  1. ServletContext
  2. ApplicationContext
  3. 各Controller持有的Context。

增加aop后,注入类实例为aop代理实例。
接口:BeanFactory、ApplicationContext
获取ApplicationContext,实现ApplicationContextAware。
手动注入bean:

  1. BeanDefinitionRegistry+BeanDefinitionBuilder。
  2. AutowireCapableBeanFactory#autowire()。装配对象
    DefaultListableBeanFactory#registerSingleton();注册为bean

1.2 Container Overview

容器通过样板文件,自动引入。
bean配置:xml文件、javaConfig、groovyConfig;
引入配置:import标签、@Import、@ImportResource
ApplicationContext#getBean(),获取bean

1.3 Bean Overview

IOC容器中bean表现为BeanDefiniton Objects;元数据:类名、生命周期和范围、依赖、属性配置。
运行时手动配置bean,非官方支持:
ApplicationContext,getAutowireCapableBeanFactory();强转类型DefaultListableBeanFactory。
DefaultListableBeanFactory#registerSingleton()/registerBeanDefinition();
bean命名、别名,均可唯一标识bean。
初始化:构造器、静态工厂、实例工厂。

1.4 Dependencies

构造器注入(强制依赖项)、属性注入(可选依赖项,避免循环依赖)。
@Autowired(requred=true)强制依赖。
@DependsOn、@Lazy、@Conditional族、@AutoConfigureAfter、@AutoConfigureOrder;条件化加载
单例bean注入非单例bean,抽象类bean方法注入;@Lookup。

1.5 Bean Scopes

singleton、prototype、request、session;application、websocket
有会话状态bean使用prototype,无状态用singleton。
spring不负责prototype bean的销毁,需手动释放资源。
request、session;application、websocket;ApplicationContext的web实现类支持,其他容器不支持。对应注解:@RequestScope、@SessionScope、@ApplicationScope。

1.6 Customizing The Nature of a Bean

定制方式:callback、Aware类接口
初始回调:@PostConstruct、InitializingBean、init-method/default-init-method。
销毁回调:@PreDestroy、DisposableBean、destroy-method/default-destroy-method。
LifeCycle接口,context启动、关闭时回调。
ApplicationContextAware,获取ApplicationContext
BeanNameAware,设置bean name。
使用Aware类接口,会耦合spring api;尽量只用于基础架构bean。

1.7 Bean Definition Inheritance

xml配置:parent、abstract
javaConfig:父类抽象,注入属性;子类配置为bean。
如父类不标记为抽象,容器会预实例化父类。

1.8 Container Extension Points

BeanPostProcessor,特殊启动,处理初始化后的bean;aop采用BeanPostProcessor实现。

  1. 顺序,继承Ordered接口。
  2. postProcessBeforeInitialization();初始化前调用
  3. postProcessAfterInitialization();初始化后调用

BeanFactoryPostProcessor,读取、修改配置元数据;类似BeanPostProcessor。

  • postProcessBeanFactory();读取配置元数据后调用

FactoryBean,工厂bean;工厂bean实例id为"&id","id"为工厂bean返回bean实例的id

  • getObject();
  • isSingleton();
  • getObjectType()

1.9 Annotation-based Container Configuration

注解配置先于xml配置解析,可以被xml配置覆盖。即xml优先。
@Scope;作用域
@DependsOn、@AutoConfigureAfter/@AutoConfigureBefore、@AutoConfigureOrder;装配顺序
@Conditional族;装配条件
@PostConstruct、@PreDestroy;回调
@Required、@Autowired、@Primary、@Qualifier;属性装配
泛型装配list、map。配合策略模式使用。

1.13 Environment Abstraction

Environment整合profiles、properties。
@Profile,版本注解,对应spring.profile.active;可使用运算符:&、|、!,()括起子表达式。
xml中为beans profile属性。
StandardEnvironment,包含JVM属性、系统属性、配置属性。
System.getProperties();JVM属性
System.getenv();系统属性,可被JVM属性覆盖,-D指定。
@PropertySources、@PropertySource;导入配置文件
占位符,${expr:defaultValue};
占位符解析,PropertyPlaceholderConfigurer,BeanFactoryPostProcessor实现类。

1.15 Additional Capabilities of ApplicationContext

MessageSource;格式化信息。
ApplicationEvent、ApplicationEventPublisher、ApplicationListener;事件发布、监听
@EventListener,不实现ApplicationListener时标记监听方法,value、condition。若监听方法返回事件,则发布。
@Async,标记监听器方法,异步处理,可通过发布事件通知处理结果。事件监听器默认为同步,所有监听器处理完事件后,发布器才能继续发布事件,否则阻塞。
ResourceLoader;资源加载

  • 实现ResourceLoaderAware、或注入获取,
  • getResource()/getClassLoader();

2,Resources

Resource接口,继承InputStreamSource。实现类:UrlResource、ClassPathResource、FileSystemResource、ServletContextResource、InputStreamResource、ByteArrayResource。
前缀:classpath:、classpath*:、http:、ftp:、file:;与路径间无空格。
路径通配符:*、**
注意:

  • file:path、path;均为相对项目根目录的路径,
  • file:///path;绝对路径

3,Validation、Data Binding、Type Conversion

验证:

  • Validator接口,spring包下,验证数据。
  • 基于注解的校验,hibernate注解:@NotNull、@Size…
  • 自定义注解,@Constraint引用验证类。

BeanWrapper、BeanWrapperImpl;设置数据。

  • setPropertyValue();

格式化注解:@NumberFormat、@DateTimeFormat

4,SpEL

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(“spel”);
String message = (String) exp.getValue();
${expr},占位符;解析配置元数据时解析。
#{expr},SpEL运算。

5,Aspect Oriented Programming with Spring

@EnableAspectJAutoProxy;开启
@Aspect+@Component;声明切面
@Pointcut;切点
@Before、@After、@AfterThrowing、@AfterReturning、@Around;通知

4 Data Access

1,Transaction Management

1.1 Transaction Model

全局事务管理,JTA,复杂,需与JDNI配合;可跨资源。
本地事务管理,不可跨资源。
Spring事务管理整合了两者;配置对应的PlatformTransactionManager bean。

1.2 Spring Transaction Abstraction

PlatformTransactionManager、TransactionStatus(执行)、TransactionDefinition(定义)。

  • TransactionDefinition;定义:propagation、isolation、timeout、read-only。

1.3 Synchronizing Resources with Transactions

spring注入的查询bean,绑定事务bean;通过注解开启即可。

1.4 Declarative transaction management

@EnableTransactionManagement,order属性指定优先级
@Transactional,spring包下;可配置transactionManager属性。

1.5 Programmatic Transaction Management

TransactionTemplate、或实现PlatformTransactionManager。
减少连接占用时间。

3,Data Access with JDBC

JdbcTemplate;支持?占位符
NamedParameterJdbcTemplate;占位符格式":varName",传入Map作为参数。

5 Web Servlet

Servlet-stack web application built on the servlet API and deployed on servlet container.

1,Spring Web MVC

1.1 DispatcherServlet

context:servletContext、ApplicationContext(WebApplicationContext)
WebApplicationContext是ApplicationContext的扩展,Root WebApplicationContext存放公共bean,如中间件、ORM、service等;Servlet WebApplicationContext存放servlet相关bean,如controller、handlerMapping、ViewResolver等。
RequestContextUtils获取context,RequestContextHolder获取request、response等。

  • RequestAttributes ra=RequestContextHolder.getRequestAttributes();
  • HttpServletRequest request=((ServletRequestAttributes) ra).getRequest();
  • ApplicationContext ac=RequestContextUtils.findWebApplicationContext(request);

如不要求层级性,可不设置contextConfigLocation;应用只创建Root WebApplicationContext。
MVC Config:HandlerMapping、ViewResolver、MultipartResolver、HandlerExceptionResolver等。
Servlet Config:filter、AsyncSupport等。
springboot中MVC Config、Servlet Config,继承WebMvcConfigurationSupport配置相应信息。
request请求过程:绑定WebApplicationContext;绑定LocaleResolver、ThemeResolver、MultipartResolver;handlerMapping;
HandlerInterceptor:

  • preHandle();前处理,true则继续,false直接返回
  • postHandle();后处理,对@ResponseBody、ResponseEntity类方法无效;此时实现ResponseBodyAdvice,标记ControllerAdvice。
  • afterCompletion()

ExceptionHandler,异常处理;自定义:@ControllerAdvice、@ExceptionHandler、@ResponseStatus。
error page,增加拦截器,重定向异常到指定路径。
View Resolve;重定向redirect:、RedirectView,跳转forward:。
打印请求详细信息,配置enableLoggingRequestDetails true。

1.3 Annotated Controllers

声明:@Controller、@RestController
映射:@RequestMapping、@GetMapping、@PostMapping等
参数:@RequestParam、@RequestBody、@PathVariable("/owners/{ownerId}/pets/{petId}")
Request Mapping
url通配符:?一个字符,*一层中的任意字符,**任意层;${}占位符
路径参数匹配:{name:reg},匹配url中指定正则的部分作为参数。
模式比较:路径参数、?、1分,**两分;多匹配模式中,选择分值高、长度长、通配符多的模式。/**始终最后。AntPathMatcher.getPatternComparator()做匹配。
后缀匹配:/path默认匹配/path.
;可通过查询参数避免匹配
media type约束:consumes–Content-Type,produces–Accept;MediaType常量获取类型,支持!运算符;可在类上声明media约束,方法的media约束对类约束是重写,而非扩展。
header、parameter约束:key/!key,有/没有key参数;key=value,key参数值必须为value
对应@RequestMapping属性:path、consumes/produces、headers/params
Handler Method
获取值:@RequestParam、@PathVariable、@RequestBody、@RequestHeader、@CookieValue、@ModelAttribute、@SessionAttribute、@RequestAttribute
@ModelAttribute,参数装配为对象、或添加model属性,DataBinder;BindingResult,绑定结果
@RequestMapping,redirectAttributes属性,标记重定向属性;默认model属性。
RequestContextUtils,通过FlashMap传递重定向属性。
接收文件,MultipartFile、List、Map<String,MultipartFile>
@ResponseBody、ResponseEntity;返回声明
@JsonView,自定义json方式。
Controller Advice
@ControllerAdvice、@RestControllerAdvice,@ExceptionHandler
通过属性,指定范围。

1.4 URI Links

URI、UriComponents、UriComponentsBuilder

1.5 Asynchronous Requests

释放容器线程,提高吞吐量。
WebMvcConfigurerSupport配置异步支持。
声明
返回结果为DeferredResult、Callable、ResponseBodyEmitter;需配置容器的异步支持,持有response,异步返回。
@EnableAsync、@Async;异步调用,立即返回。
长连接,考虑WebSocket、AsyncContext。

1.6 CORS

HandlerMapping判定,拒绝不符合CORS配置的请求;浏览器判定,拒绝无CORS头的返回。
后台配置
@CrossOrigin,后台CORS默认:All origins、All headers、所有方法。
WebMvcConfigurerSupport,后台CORS默认:All origins、All headers、GET/POST/HEAD。
通过Filter,增加Access-Control-Allow-Origin;防止浏览器拒绝

1.8 HTTP Caching

ResponseEntity.ok().cacheControl(cacheControl)。
Cache-Control;缓存策略。no-store、no-cache、private、public、max-age、min-fresh、max-state
ETag、Last-Modified;标记字段
if-Match、if-None-Match、if-Modified-Since、ifUnmodified-Since;判定字段

1.10 MVC Config

springboot继承WebMvcConfigurerSupport。
Type Conversion
addFormatter();增加转换、格式化;Number、Date默认添加。
Validator
springboot默认使用hibernate validator。
WebMvcConfigurerSupport#getValidator();返回自定义validator
Interceptors
addInterceptor();可增加多个拦截器;默认拦截所有请求
Message Converters
configureMessageConverters();覆盖
extendMessageConverters();扩展
路径映射
addViewControllers();controller映射
addResourceHandlers();资源路径映射

2,REST Clients

RestTemplate,synchronous
WebClient,non-blocking

6 Integration

整合模型、运行过程、配置
IoC、AOP。

1,Remoting and Web Services with Spring

暴露接口、发现接口、通信协议、处理过程
RMI
Remote Method Invocation。
RmiServiceExporter,暴露接口;属性:serviceName、service、interface、registryPort
RmiProxyFactoryBean,连接远程接口,获取实例;serviceUrl(rmi://host:registryPort/serviceName)、serviceInterface。
无默认的安全、事务。重量级。
HTTP Invokers
HttpInvokerServiceExporter,暴露接口;service、serviceInterface
HttpInvokerProxyFactoryBean,连接接口;serviceUrl、serviceInterface
JMS用于集群。
REST Endpoints
RestTemplate、WebClient

3,JMS (Java Message Service)

JmsTemplate,类似JDBC的简化。连接、事务、执行;production、consumption。
ConnectionFactory、JmsTransactionManager、JmsTemplate、MessageListenerContainer/MessageListener
listener方法消费消息失败,回滚。

4,JMX(Java Management Extensions)

暴露、配置、管理
Exporting Your Beans to JMX
MBeanExporter、MBeanServer;默认暴露public成员。
tomcat提供MBeanServer bean;也可通过MBeanServerFactoryBean配置。
RegistrationPolicy,注册策略;FAIL_ON_EXISTING、IGNORE_EXISTING、REPLACE_EXISTING
@EnableMBeanExport、@ManagedResource、@ManagedAttribute、@ManagedOperation/@ManagedOperationParameter、@ManagedOperationParameters
NotificationListener、NotificationPublisherAware;监听、发布MBean变动。
Connectors
ConnectorServerFactoryBean;server-side,默认:service:jmx:jmxmp://localhost:9875
MBeanServerConnectionFactoryBean;client-side,填写url

6,Email

核心类:MailSender、SimpleMailMessage
spring:JavaMailSender、MimeMessagePreparator、MimeMessageHelper
复杂邮件,使用FreeMarker等模板构建显示内容。
MailSender配置host、port(默认25)、username、password。

7,Task Execution and Scheduling

TaskExecutor/TaskScheduler、策略、Task
TaskExecutor
SyncTaskExecutor、SimpleAsyncTaskExecutor、ConcurrentTaskExecutor、ThreadPoolTaskExecutor
execute();提交任务
TaskScheduler
根据策略执行,返回SchedulerFuture。
执行器:ConcurrentTaskScheduler、ThreadPoolTaskScheduler。容器相关。
策略接口:Trigger、TriggerContext;常用实现类:CronTrigger、PeriodicTrigger。
Annotation
@EnableAsync、@Async;异步执行,默认proxy mode。提交spring TaskExecutor执行,无返回或返回Future。
@EnableScheduling、@Scheduled;策略执行。@Scheduled方法无返回、无形参。
Using the Quartz Scheduler
核心类:Scheduler、Trigger、Job/JobDetail;任务绑定于策略。
SpringBeanJobFactory,重写createJobInstance();调用父类方法构建job,注入为bean
ac.getAutowireCapableBeanFactory().autowireBean(obj);装配obj为bean
SchedulerFactoryBean,new+设置JobFactory;使用自动装配的jobDetail。

8,Cache Abstraction

Buffer缓冲,适配高低速;Cache缓存,存储查询结果便于后续快速使用
核心类:CacheProvider、CacheManager、Cache、Entry、Expiry
注解 :@CacheConfig、@Caching、@Cacheable、@CachePut、@CacheEvit

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值