




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Spring5.0源码深度解析课程安Spring5.0事务源码分Spring5.0AopSpring5.0、SpringMVCSpringBoot2.0余老 Spring框架快速入什么Spring框SpringJavaIoC(InversionofControlAOP(AspectOrientedProgramming,面NewUserService();Spring体系结1、SpringCore:BeanFactoryJavaBean(IOC)模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。2、SpringAOP:集成了面向切面的编程功能(AOP可以将性事物管理集成到应用程序中。3、SpringCntext:一个配置文件,为Spring框架提供上下文信息4、SpringDo:Spring5、SpringORM:Spring集成了各种orm(objectrelationshipmap对象关系映射6、SpringWebweb(Struts、7、SpringwebMVC:Springweb思考一个问题为什么启动SpringBoot项目的时候需要加上Configuration快速构建Spring环Maven依赖信<artifactId>spring-Xml方式环境搭<beanid="userEntity"<beanid="userEntity"<propertyname="userId"<propertyname="userName"<beans" " " bean对publicclasspublicclassUserEntity{privateIntegeruserId;privateStringuserName;publicUserEntity(IntegeruserId,StringuserName)this.userId=this.userName=}publicvoidsetUserId(IntegeruserId)this.userId=}publicvoidsetUserName(StringuserName)this.userName=}publicStringtoString()return"UserEntity{""userId="+userId",userName='"+userName+'\''}}Spring启动 spring配置文件,IOC容ClassPathXmlApplicationContextclassPath=new//UserEntityuserEntity=(UserEntity)classPath.getBean("userEntity");注解方式环境搭Configuration配置容publicpublicclassMySpringConfig//@Configuration等同于配置的spring配置文publicUserEntityuserEntity()returnnewUserEntity(10,}}publicclassUserEntity{privateIntegeruserId;privateStringuserName;publicUserEntity(IntegeruserId,StringuserName)this.userId=this.userName=}publicIntegergetUserId()return}publicStringgetUserName()return}publicvoidsetUserId(IntegeruserId)this.userId=}publicpublicvoidsetUserName(StringuserName)this.userName=}}使用注解形式形式加载privateprivatestaticAnnotationConfigApplicationContextpublicstaticvoidmain(String[]args)applicationContext=newAnnotationConfigApplicationContext(MySpringConfig.class);UserEntityuserEntity=applicationContext.getBean("userEntity",UserEntity.class);}@ComponentScan用扫包下注入springIOC容器publicclassMySpringConfig{//@Configuration等同于配spring配置文publicUserEntityuserEntity()returnnewUserEntity(10,}}privateprivatestaticAnnotationConfigApplicationContextpublicstaticvoidmain(String[]args)annotationConfigApplicationContextannotationConfigApplicationContext=newAnnotationConfigApplicationContext(MySpringConfig.class);UserServiceuserService=annotationConfigApplicationContext.getBean("userService",UserService.class);System.out.println("userService:"+userService);System.out.println("以下为IOC容器注入成功的对象String[]beanDefinitionNames=for(inti=0;i<beanDefinitionNames.length;i++){}}FilterType有四种类型ASPECTJAspectj@ComponentScan(value@ComponentScan(value="com.mayikt.v2",includeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION,=Controller.class)},useDefaultFilters=false)publicclassMySpringConfig{//@Configuration等同于配spring配置文publicUserEntityuserEntity()returnnewUserEntity(10,}}@ComponentScan(value@ComponentScan(value="com.mayikt.v2",excludeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION,=Controller.class)},useDefaultFilters=true)publicclassMySpringConfig{//@Configuration等同于配spring配置文publicUserEntityuserEntity()returnnewUserEntity(10,}}}SpringsingletonprototypeBeanrequestBeanBeanHttp请session作用域表示煤气请求都会产生一个新的BeanBean仅在当前HttpUserServiceUserServiceuserService1=annotationConfigApplicationContext.getBean("userService",UserServiceuserService2=annotationConfigApplicationContext.getBean("userService",结果为Lazy表示为懒加载,当真正需要获取的时候才会被加True表示为懒加载false表示为在IOC容器加载的时候被创建publicclassUserServicepublicUserService()System.out.println("UserService无参数构造被加载}}}Condition是在spring4.0增加的条件注解,通过这个可以功能可以实现选择性的注入Bean操作,接下来先学习下Condition是如何使用的,然后分析spring源码了解其中的实SpringWIN7win7publicpublicclassMyConditionimplementsCondition根据条件判断上下文*@param@parampublicbooleanmatches(ConditionContextcontext,AnnotatedTypeMetadatametadata)1.获取当前环境配Environmentenvironment=context.getEnvironment();StringosName=environment.getProperty("");if(osName.equals("Windows7")){true就是能够创建该return}return}}publicWin7Entitywin7Entity(){returnnew}@Import注@Import@Configurationbean@Import({V5UserEntity.class,默 beanid@Import({V5UserEntity.class,publicpublicclassMyImportSelectorimplementsImportSelectorAnnotationMetadata注解信*@param//添加需 的spring容器的returnnew}}@public@interfaceEnableUser}publicclassMyImportBeanDefinitionRegistrarimplementspublicclassMyImportBeanDefinitionRegistrarimplementsImportBeanDefinitionRegistrarpublicpublicvoidregisterBeanDefinitions(AnnotationMetadataimportingClassMetadata,BeanDefinitionRegistryregistry)//手 StringbeanName=RootBeanDefinitionrootBeanDefinition=newRootBeanDefinition(PayEntity.class);registry.registerBeanDefinition(beanName,rootBeanDefinition);}}publicpublicclassMyFactoryBeanimplementsFactoryBean<MemberEntity>publicMemberEntitygetObject()throwsExceptionreturnnew}publicClass<?>getObjectType()return}publicbooleanisSingleton()return}}publicMyFactoryBeanmyFactoryBean()returnnew}区别:BeanFactory是个Factory,也就是IOC容器或对象工厂,FactoryBean是个Bean。SpringBeanBeanFactoryIOCFactoryBean而言,这个Bean不是简单的Bean,而是一个能生产或者修饰对象生成的工厂SpringBean的生命周期总refresh();getBean()→doGetBean()→createBean()→doCreateBean()→createBeanInstance(初始化对JavaCGLIBinvokeAwareMethods()awareapplyBeanPostProcessorsAfterInitializationSpringAop源码分AspectJAutoProxyRegistrar中会对象BeanClass:AnnotationAwareAspectJAutoProxyCreatorAutoProxyCreator有是 AutoProxyCreator经过这样的一个类。判断该被对象是否有被有实现过接口,如果有实现过接口就使用jdk动态,如果没有实现接口则使用cglib动态。MethodInterceptor(每个通知)invoke模拟SpringAop五个通知调用链关UserService接publicpublicclassUserServicepublicvoidlogin(StringuserName,Stringage){System.out.println("userName:"+userName+",age:"+age);}}创建方法接publicpublicinterfaceMethodInterceptor执行通知*@paramObjectinvoke(MethodInvocationmethodInvocation)throwsInvocationTargetException,}创建前置通publicpublicclassBeforMethodInterceptorimplementsMethodInterceptorpublicObjectinvoke(MethodInvocationmethodInvocationthrowsInvocationTargetExceptionIllegalAccessExceptionreturnmethodIcess();//目标方}}创建后置通publicpublicclassAfterMethodInterceptorimplementsMethodInterceptorpublicObjectinvoke(MethodInvocationmethodInvocation)InvocationTargetException,IllegalAccessExceptionObjectprocessmethodIcess();return}}创建环绕通publicpublicclassAroundMethodInterceptorimplementsMethodInterceptorpublicObjectinvoke(MethodInvocationmethodInvocation)throwsInvocationTargetException,IllegalAccessException{ Objectprocess=System.out.println("环绕通知之后执 return}}创建方法执行接publicpublicinterfaceMethodInvocation方法调用个通知的方*Objectprocess()throwsInvocationTargetException,}publicclassDefaultMethodInvacationimplementsMethodInvocationprivateList<MethodInterceptor>chian;privateObjecttarget;//目标对象privateMethodmethod;//目标方法privateObjectargs[];//目标参数publicDefaultMethodInvacation(List<MethodInterceptor>chian,Objecttarget,Methodmethod,Object[]args)this.chian=chian;this.target=target;this.method=method;this.args=args;}publicObjectprocess()throwsInvocationTargetException,IllegalAccessExceptionif(currentChianIndex==chian.size())执行目标returnreturnmethod.invoke(target,}MethodInterceptormethodInterceptor=//return}}Spring事务底层源码分SpringAop基本环境搭Maven依赖信<artifactId>spring-mysql<artifactId>mysql-connector-<artifactId>spring-publicclassMyConfig{publicDataSourcedataSource()MysqlDataSourcemysqlDataSource=newMysqlDataSource();return}publicJdbcTemplatejdbcTemplate()returnnew}publicPlatformTransactionManagertxManager()returnnew}}publicclassOrderDao{privateJdbcTemplatepublicvoidaddOrderInfo()jdbcTemplate.update("insertintoorder_info}}Spring事务源码分Aop实现一样的功能。Ioc容器中TransactionInterceptor是 ifif(txAttr==null||!(tminstanceofCallbackPreferringPlatformTransactionManager))开启事TransactionInfotxInfo=createTransactionIfNecessary(tm,txAttr,joinpointIdentification);ObjectretVal=null;try执行目标方retVal=}catch(Throwableex)//回滚当前事务completeTransactionAfterThrowing(txInfo,ex);throwex;}finally}returnretVal;}纯手写SpringAop环绕通知+手动事务就可以事SpringAop中所有最终是如何执行?调用链关AutoProxyCreator使用该类创建目标对象(TransactionInterceptor事务@EnableTransactionManagementePROXY: Beanid:Value:ProxyTransactionManagementConfiguration将一下对象到ioc容Value:tansactionInterceptorInfrastructureAdvisorAutoProxyCreator就是我们的后置处理Bean对象在初始化之后都会判断是否需要创建类(根据是否有加上InfrastructureAdvisorAutoProxyCreator就 serviceSpring循环依赖原什么Spring循环依赖问如何解决Spring循环依赖相关业务逻辑代publicclassAService{ privateBServicepublicvoidsetbService(BServicebService)this.bService=}}publicclassBService{ privateAServicepublicvoidsetaService(AServiceaService)this.aService=}}如何底层解决循环依赖原循环依赖中完整对象信Map<String,Object>singletonObjects一级缓存完成对象(对象和属性都已经赋值)Map<String,Object>earlySingletonObjects性缺没有赋值早期对象Map<String,ObjectFactory<?>>singletonFactories三级缓存(只初始化,没有给属性赋值对象)存放提前对象AB依赖与BBAASpringBeanA(单例的情况doGetBeanStringbeanNameStringbeanNameObjectFactory<?>singletonFactorycreateBean→doCreateBeancreateBeanInstancecglib(注意对象不完整,因为熟悉没有duGetBean1-6BAgetSingletonAapplyPropertyValues→valueResolver.resolveValueIfNecessary→resolveReference(argName,ref)init(初始化HashMap<Object,HashMap<Object,Object>objectHashMap=newHashMap<Object,1.A对objectHashMap.put("aService",new//2.B对象从三级缓存中查找到objectHashMap.put("bService",newAServiceaService=(AService)objectHashMap.get("aService");BServicebService=(BService)objectHashMap.get("bService");bService.aService=aService;//3.A对象需要设aService.bService=protectedprotectedObjectgetSingleton(StringbeanName,booleanallowEarlyReference)1.ObjectsingletonObject=//2.没有创建对象,并且该对象正在创建(标记为循环依赖的查询if(singletonObject==null&&isSingletonCurrentlyInCreation(beanName))//3.singletonObject=this.earlySingletonObjects.get(beanName);if(singletonObject==null&&allowEarlyReference){//4.ObjectFactory<?>singletonFactory=this.singletonFactories.get(beanName);if(singletonFactory!=null){singletonObject=singletonFactory.getObject();this.earlySingletonObjects.put(beanName,singletonObject);}}}}returnprotectedprotectedvoidaddSingletonFactory(StringbeanName,ObjectFactory<?>singletonFactory){Assert.notNull(singletonFactory,"Singletonfactorymustnotbenull");if(!this.singletonObjects.containsKey(beanName)){this.singletonFactories.put(beanName,singletonFactory);}}},BAABBAbeaniscurrentlyincreation:IsthereanunresolvablecircularABBABBABABAABSpringBean创建AdoGetBeangetSingleton(StringgetSingleton(StringbeanName,ObjectFactory<?>singletonFactory)this.singletonsCurrentlyInCreation.add(beanName)createBeanInstancecglibbeanaddSingletonFactorypopulateBeanABBBAprotectedvoidaddSingleton(StringbeanName,ObjectsingletonObject){synchronized(this.singletonObjects){this.singletonObjects.put(beanName,publicObjectprotectedprotectedvoidaddSingletonFactory(StringbeanName,ObjectFactory<?>singletonFactory){Assert.notNull(singletonFactory,"Singletonfactorymustnotbenull");//判断一级缓存是否存if(!this.singletonObjects.containsKey(beanName))//将该不完整的对象存放到三级缓存集合中this.singletonFactories.put(beanName,singletonFactory);}}}protectedprotectedObjectgetSingleton(StringbeanName,booleanallowEarlyReference)//1.一级缓存bean对象该集合缓存的对象为完整对象对象创建完毕并且已经属性赋值成功ObjectsingletonObject=if(singletonObject==null&&isSingletonCurrentlyInCreation(beanName))//2.从二级缓存中获取对象信singletonObject=this.earlySingletonObjects.get(beanName);if(singletonObject==null&&allowEarlyReference){3.从三级缓存中获取对ObjectFactory<?>singletonFactory=this.singletonFactories.get(beanName);if(singletonFactory!=null){singletonObjectsingletonObject=//4.如果三级缓存中存在对象的时候下,就返回二级缓存中。this.earlySingletonObjects.put(beanName,singletonObject);}}}}return}SpringIOCAOP依赖注入赋值ABB对象BAAspringSpringBeanAservicgetSingleton(beanName)singletonObjects一级缓存完整对象earlySingletonObjectssingletonFactories三级缓存存放婴儿对象婴儿对象(提前对象){}singletonsCurrentlyInCreationgetSingleton(StringbeanName,ObjectFactory<?>singletonFactory)this.singletonsCurrentlyInCreation.add(beanName)表示该对象已经开始创建createBean() 赋值的)存放三级缓存中。ABABBprotectedprotectedvoidaddSingletonFactory(StringbeanName,ObjectFactory<?>singletonFactory){Assert.notNull(singletonFactory,"Singletonfactorymustnotbenull");//如果一级缓存没有该对象的情if(!this.singletonObjects.containsKey(beanName))//将该对象存放到三级缓存中婴儿对象this.singletonFactories.put(beanName,singletonFactory);}}}protectedprotectedObjectgetSingleton(StringbeanName,booleanallowEarlyReference)//1.一级缓存对象集合(缓存完整对象)对象已经创建成功呢并且所有的属性都已经赋值成ObjectsingletonObject=2.如果已经缓存没if(singletonObject==null&&isSingletonCurrentlyInCreation(beanName))//查询二级缓存是否有缓存对singletonObject=this.earlySingletonObjects.get(beanName);if(singletonObject==null&&allowEarlyReference){//4.查询三级缓存,三级缓存如果有的情况ObjectFactory<?>singletonFactory=this.singletonFactories.get(beanName);if(singletonFactory!=null){singletonObject=//将三级缓存中的数据放入到二级缓存中this.earlySingletonObjects.put(beanName,singletonObject);}}}}return}SpringMVC源码分Servlet开发基本环Servlet简单的介SunAPIservletwebJava2ServletServletSpringMVC关idea快速创建一个Servlet项创建的mavenweb工厂发现没有 ,则创建XML方 publicclassMyServletextendsHttpServletprotectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)ServletException,IOException{resp.getWriter().print("thisismayikt");}}基于注解方publicclassMyServletextendsHttpServletprotectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)ServletException,IOException{resp.getWriter().print("thisismayikt");}}Servlet线程是否答案:不安全,Servlet是单例的在高并况下,可能会存程安全问publicclassMyServletextendsHttpServletprivateIntegercount=publicMyServlet(){}protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOExceptiontry{}catch(Exceptione)}resp.getWriter().print("thisismayiktcount:"+}}在web容器启动时为提供给第组件机会做一些初始化的工作,例如servlet或filtes等,servletServletContainerInitializer每个框架要使用ServletContainerInitializer就必须在对应的jar包的META-INF/services 建一个名为javax.servlet.ServletContainerInitializer的文件,文件内容指定具体的ServletContainerInitializer实现类。1、Servlet容器扫描,当前应用里面每一个jar包ServletContainerInitializer2ServletContainerInitializerServletContainerInitializer实现类的全类名;相关代@author蚂蚁课堂创始人@title:@description:每特教育独创第五期互联网架构课@date@HandlesTypes(value=publicclassMyServletContainerInitializerimplementsServletContainerInitializer*@param 类型也就是MyHandlesType所有子类@param@throwspublicvoidonStartup(Set<Class<?>>set,ServletContextservletContext)throwsServletException//1.打印所有 的类forfor(Class<?>c:set){}//2.servletContext手动过滤器 ServletRegistration.DynamicpayServlet=servletContext.addServlet("payServlet",newPayServlet());}}基于xml方式启Maven依赖信publicclassMyMvcConfig}配置文件内publicpublicclassWebInitializerimplementsWebApplicationInitializerpublicvoidonStartup(javax.servlet.ServletContextservletContext)ServletException 创建SpringMVC容AnnotationConfigWebApplicationContextapp=//2.我们的配置文 我们DispatcherServletdispatcherServlet=newDispatcherServlet(app);ServletRegistration.Dynamicdynamic=servletContext.addServlet("dispatcherServlet",dispatcherServlet);dynamic.setLoadOnStartup(1);//最优先启}}}Jsp视图publicpublicViewResolverviewResolver()InternalResourceViewResolverinternalResourceViewResolver=new前internalResourceViewResolver.setPrefix("/WEB-//后缀returninternalResourceViewResolver;}<%@pagelanguage="java"contentType="text/html;charset=UTF-我是完全注解方式整合SpringMVC器使用器和过滤器都是基于Aop实现,能够对请求执行之前和之后实现。ServletWeb器不需要依赖于Servlet、不仅可以实现Web请求还有其他方法等SpringMVC器的使1.自定义请求pletion在DispatcherServletpublicpublicclassTokenInterceptorimplementsHandlerInterceptorpublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponsere
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 供应链质量管理实务操作指南
- 2025年市场营销学课件:理论与中国市场
- 三农村公共服务均等化与便捷化实施方案
- 网络安全应急响应处理手册
- 集成开发环境使用说明书
- 实习员工劳务合同
- 法律服务保密协议书
- 地产行业投资项目表
- 动态字体大小调整实现办法
- 保洁服务招标合同
- 2025年中国春节档市场报告-拓普数据-
- 2025年山西省太原市卫健委直属单位招聘522人历年高频重点模拟试卷提升(共500题附带答案详解)
- 劳务合同协议书书
- 白城2025年吉林大安市事业单位面向上半年应征入伍高校毕业生招聘5人笔试历年参考题库附带答案详解
- 全球人工智能产业发展现状和趋势
- 2025年内蒙古化工职业学院高职单招职业技能测试近5年常考版参考题库含答案解析
- 民法典解读之婚姻家庭编
- 2025年菏泽医学专科学校高职单招数学历年(2016-2024)频考点试题含答案解析
- 2025年漯河职业技术学院高职单招职业技能测试近5年常考版参考题库含答案解析
- Unit 2 What time is it?-A Let's spell(课件)-2024-2025学年人教PEP版英语四年级下册
- 2024-2025学年人教版数学六年级下册第二单元百分数(二)(含答案)
评论
0/150
提交评论