Spring注解驱动开发
容器
AnnotationConfigApplicationContext
- 配置类
- 包扫描
组件添加
- @ComponentScan
-
@Bean
- 指定初始化销毁
-
初始化其他方式
- InitializingBean(初始化设置值之后)
- DisposableBean(销毁)
-
JSR250
- @PostConstruct
- @PreDestroy
- BeanPostProcessor
- @Configuration
- @Component
- @Service
- @Controller
- @Repository
- @Conditional
- @Primary
- @Lazy
- @Scope
- @Import
- ImportSelector
-
工厂模式
-
FactoryBean
- &beanName获取Factory本身
-
组件赋值
- @Value
-
@Autowired
- @Qualifier
-
其他方式
- @Resources(JSR250)
- @Inject(JSR330,需要导入javax.inject)
- @PropertySource
- @PropertySources
-
@Profile
- Environment
- -Dspring.profiles.active=test
组件注入
- 方法参数
- 构造器注入
-
ApplicationContextAware
-
ApplicationContextAwareProcessor
if (bean instanceof Aware) {
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } }
-
- xxxAware
AOP
- @EnableAspectJAutoProxy
- @Before/@After/@AfterReturning/@AfterThrowing/@Around
- @Pointcut
声明式事务
- @EnableTransactionManagement
- @Transactional
扩展原理
BeanFactoryPostProcessor
- Spring容器标准初始化之后执行(BeanPostProcessor之前),此时bean还未创建
-
Spring容器初始化两大步
- 1、加载保存和读取所有bean配置
- 2、按照之前的配置创建bean
BeanDefinitionRegistryPostProcessor
- BeanFactoryPostProcessor子类,可自定义添加bean定义
-
BeanDefinetionRegistry
- BeanDefinetionBuilder
ApplicationListener
- @EventListener
Spring容器创建过程
web
servlet3.0
- ServletContainerInitializer
-
Registration
- ServletRegistration
- FilterRegistration
- ServletContext
异步请求
-
servlet3.0异步处理
在Servlet 3.0之前,Servlet采用Thread-Per-Request的方式处理请求。
即每一次Http请求都由某一个线程从头到尾负责处理。
如果一个请求需要进行IO操作,比如访问数据库、调用第三方服务接口等,那么其所对应的线程将同步地等待IO操作完成, 而IO操作是非常慢的,所以此时的线程并不能及时地释放回线程池以供后续使用,在并发量越来越大的情况下,这将带来严重的性能问题。即便是像Spring、Struts这样的高层框架也脱离不了这样的桎梏,因为他们都是建立在Servlet之上的。为了解决这样的问题,Servlet 3.0引入了异步处理,然后在Servlet 3.1中又引入了非阻塞IO来进一步增强异步处理的性能。
- 返回Callable
- 返回DeferredResult