




已阅读5页,还剩21页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1 前言 本文档是关于Spring框架开发风格分析性文档。包括:基本概念、设计原则、设计规范、重要功能分析、关键类分析等。本文档适合所有Java开发人员。2 概念a) 装配:创建系统组件之间协作关系的这个动作。b) Spring坚持的信念: i. 好的设计比实现技术重要。 ii. 通过接口松散耦合的JavaBeans是个很好的模型。 iii. 代码应该容易测试。c) Spring的特性: i. Spring:是一个轻量级的IoC和AOP容器框架。 ii. 反向控制IoC:对象是被动接收依赖类而不是主动的查找。可以将IoC理解为JNDI的反转对象不是从容器中查找他的依赖类,而是容器在实例化对象的时候主动将它的依赖类注入给它。 iii. AOP面向切面:系统对象只做他们该做的业务逻辑,不负责(或关心)其他系统的问题(如日志和事务支持)。1. AOP经常定义为编程技术,用来在系统中提升业务的分离。2. 系统服务如日志、事务管理和安全经常融入到一些其他功能模块中。这些系统服务通常叫做交叉业务。它分布在多个组件中,给代码带来双重复杂性。a) 如果改变业务规则,需要到各个模块中去修改。即使抽象为一个模块,其他地方也得调用个方法,该方法还是分布到很多地方。b) 组件可能因为那些与核心业务无关的代码变得凌乱。d) AOP帮助将这些服务模块化,并把他们声明式的应用在需要它们的地方。核心业务甚至不知道他们的存在。 i. 容器:包含并管理系统对象的生命周期和配置。 ii. 框架:使用简单的组件配置组合成一个复杂的系统。Spring是代码:更加清晰、更容易管理、更容易测试。e) POJO:Plain Old Java Object, 或者:POJI: Plain Old Java Interface3 代码准则1功能类和工具类分离的原则。4 设计规范4.1 包和模块4.1.1 命名规范l 包名都采用小写字母。pertyeditorsl 类的命名要清晰准确。允许一定的长度。例如:JdbcUpdateAffectedIncorrectNumberOfRowsException4.1.2 划分方式l core包。与功能相关,是模块或子系统核心类l support包。是功能支撑性的类,来辅助或扩展core包中的类。例如:org.springframework.jdbc.core.support.core. AbstractSqlTypeValueorg.springframework.jdbc.support.CustomSQLErrorCodesTranslationl utils包。一些通用的工具,例如:日期时间工具,通常命名以utils结尾,或者是helper结尾。例如: org.springframework.util. NumberUtils。l exception包。存在异常类,对于所有可能的异常,根据分类,都可以单独进行命名。4.2 类1. Operations 接口类 i. exposing a set of common JDBC operations, whose interface is simplified throughtheuseofvarargsandautoboxing. ii. 例如:SimpleJdbcOperations 2. Accessor 辅助类 i. 不以直接使用为目的。Not intended to be used directly ii. 定义了一些主类或应用类所需要的一些属性、工具方法。例如:异常转换、基本参数等。 iii. 它通常使用于在接口和具体实现类之间。 iv. 例如:JdbcTemplate、JdbcOperations、JdbcAccessor 3. Template 模版类 i. 采用模版执行函数。定义操作的步骤。具体的业务逻辑,由子类实现,或内部类形式实现。 ii. 采用回调机制。具体的实现逻辑在回调接口的子类实现。例如:ConnectionCallback iii. 采用重载方式,支持多种参数调用形式。 iv. 处理异常,转化为统一格式的异常形式。This is the central class in the JDBC core package.*ItsimplifiestheuseofJDBCandhelpstoavoidcommonerrors.*ItexecutescoreJDBCworkflow,leavingapplicationcodetoprovideSQLandextractresults. v. 例如:SimpleJdbcTemplate、JdbcTemplate、4. Support 支持类 i. 通常封装一些工具方法,方法直接委托给工具类去实现。 ii. 可以是抽象类的形式,子类可以进行扩展。例如:DaoSupport、JdbcDaoSupport中的,getExceptionTranslator、getConnection等方法。 iii. 可以把其它组织发布的类作为自己的属性。然后添加自己的公那。 iv. 采用Delegate设计方式,启发,如果项目中,需要一些帮助类,就可以采用delegate方式,而不是采用继承的形式,这样可以保证独立演化的独立性。 v. 例如:SimpleJdbcDaoSupport、CommonsFileUploadSupport,5. Resolver 分解或解析类 i. 一些解析功能。解析字符串、请求格式等 ii. 例如:MultipartResolver、CommonsPortletMultipartResolver 继承于CommonsFileUploadSupport iii. 如果使用文件上传功能,可以配置下面类:6. Parser i. ComponentScanBeanDefinitionParser BeanDefinitionParser7. Translator 转换类或翻译类 i. 完成转换功能 ii. 可以定义为接口的形式。由具体的子类进行实现。 iii. 例如:SQLExceptionTranslator8. Custom 客户化类 i. 建议命名:custom ii. 例如:9. Aware 感知类 i. ApplicationContextAware Interfacetobeimplementedbyanyobjectthatwishestobenotifiedofthelink ApplicationContextthatitrunsin. ii. 例如:ApplicationContextAware 、ServletContextAware、ServletConfigAware10.Job 工作类 i. 对于定时性的类,可以表明该类的用途。11.Impl 实现类 i. 具体实现业务逻辑的类。当实现接口或抽象类时,可以添加这个后缀。12.Listener 监听器类 i. 监听某个事件的发生,如果发生,就可以出发一定的动作。 ii. 例如:ContextLoaderListener extends ServletContextListener完成WebApplicationContext初始化。ContextLoader类完成实际的初始化工作。13.Configurer 配置类 i. 提供配置参数、初始化数据等功能。 ii. 例如:PropertyPlaceholderConfigurer 通常在applicationContext.xml配置属性文件、Log4jConfigListener。14.Context 上下文类 i. 提供了配置功能。包括:能运行的基本属性信息、基本参数信息等。 ii. 高层通常以接口形式提供。public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver该接口继承不同的接口,代表有能力去BeanFactory、有能力装载文件资源、能够发布事件、解析参数、支持国际化等 iii. 15.Adapter 适配器类 i. 提供一个转换功能。可以使得原来不能交互的类通过该Adapter进行交互。 ii. 例如:NativeJdbcExtractorAdapter extends implements NativeJdbcExtractor16.Extractor 分离器、解析类 i. ii. 例如:ResultSetExtractor、Object extractData(ResultSet rs) C3P0NativeJdbcExtractor17.Definition 定义类 i. 定义一组常量和一些方法。 ii. 可以是接口的形式。例如:TransactionDefinition18.Editor 编辑类 i. 完成解析字符串,按照预先定义的方式解析。 ii. 例如:TransactionAttributeEditor *A+beforeanexceptionnamesubstringindicatesthattransactionsshouldcommit*evenifthisexceptionisthrown;a-thattheyshouldrollback. iii. 19.Faade 门面类 i. 提供了访问内部实现逻辑的入口。 ii. 例如:PetStoreFacade20.Assert 断言类 i. 验证执行条件是否合法。 ii. Apache commons 有此工具类 iii. 实例:ModelAndViewAssert assertCompareListModelAttribute21.Handler 处理器类 i. 完成实际的业务逻辑。Spring的 jdbcTemplate中使用这种类,完成回调工作。 ii. 例如:RowCallbackHandler 种的processRow22.Multicaster 广播类 i. 管理监听器,可以增加、删除、删除监听器, ii. Multicast the given application event to appropriate listeners.广播一个事件给某个监听器。 iii. 例如:ApplicationEventMulticaster23.Listener监听器 Observer design pattern. i. 处理监听事件 Handle an application event. ii. 例如:ApplicationListener void onApplicationEvent(ApplicationEvent event);24.Publisher 发布者类 i. 发布某个事件给全部的监听器。 ii. 例如:ApplicationEventPublishervoid publishEvent(ApplicationEvent event);25.Executor 执行者类 i. 执行任务 ii. 例如:java.util.concurrent.Executor、TaskExecutor void execute(Runnable task);26.Processor 处理器类 i. 对某个对象或对某个事件进行处理 ii. 例如: BeanFactoryPostProcessor void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;27.Generic 普通类、一般类 i. 完成通用的功能 ii. 例如:GenericApplicationContext28.Default 缺省类 i. 完成缺省功能 ii. 例如:DefaultListableBeanFactory29. Tag 标签类 i. 30.Delegating 委托类 i. 提供工具方法 ii. 实例:DelegatingActionProxy、DelegatingActionUtils31.PlugIn 插件类 i. 实例:32.Illegal 非法类 i. 例如:IllegalStateException ii. 33.Decoder 解码类 i. 实例:HtmlCharacterEntityDecoder34.References 参考类 i. 例如:HtmlCharacterEntityReferences ii. 35.Advisor i. 实例:PersistenceExceptionTranslationAdvisor36.Resource 资源类 i. 提供访问和操作资源的功能。资源比如:各种格式的文件、URL、类路径 ii. 实例:ResourceLoader 37.Loader 装载类 i. 实例:ClassLoader 38.Scanner 扫描类 i. A bean definition scanner that detects bean candidates on the classpath, ii. ClassPathBeanDefinitionScanner39.Registry 注册类 i. BeanDefinitionRegistry40.Visitor 访问者类 i. AnnotationMetadataReadingVisitor41.4.3 属性1. 从重构的角度上将,推荐使用getter/setter方式。pertyName访问形式,spring中大量使用这种方式,例如:ListImagesQuartzJob2. 对于有方向性的属性,可以命名为:from 、to、replayTo、cc3. 对于时间性的,可以以elapsed开头,例如:elapsedTime4. 缺省值,default 例如:Properties defaultStrategies5. 为谁产生什么结果,例如:Transactional(rollbackFor=Exception.class, noRollbackFor=IOException.class) 6. 参数 Log4jWebConfigurer REFRESH_INTERVAL_PARAM7. 常量定义 HttpServlet METHOD_DELETE8. 范围 SCOPE_REQUEST SCOPE_APPLICATION9. 根属性 String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + .ROOT;10. 方式 pattern如果有新旧关系,要命名两个oldPattern newPattern11. 类型 type12. 类变量 clazz4.4 方法1. 对于模版方法,要注释是该方法。通常以do开头,子类完成实际的逻辑。例如:doGetNativeConnection。 也可以在本类中完成实际逻辑,例如:getConnection () doGetConnect()2. 接口需要对函数添加注释,子类没有必要。否则,维护不方便。Eclipse方便的支持看接口或父类中的注释。3. 对于函数的参数,如果不解释,就不要现显示在函数上面,否则,没有意义。如果需要添加时,也不晚。4. 在一个函数中,调用其他关键函数时,要添加一定的注释。5. 如果标识参数非法,可以采用reject开头。例如;rejectIfNotEqualExactLength6. 对于判断性的函数,采用is开头。例如: isExistUser7. 对于加载参数,开头命名为:load 例如:loadParentContext8. 初时化信息,启动的等。开头命名为:init 、setUp例如:Log4jConfigListener中的initLogging9. 关闭服务、释放资源等。Close、Shutdown 、release、tearDown例如:Log4jWebConfigurer.shutdownLogging, releaseConnection10. 创建服务。Create 例如:createConnectionProxy11. 被初始化、被销毁。Initialized 例如:contextInitialized、contextDestroyed12. 准备做什么。AbstractTransactionalDataSourceSpringContextTests 类中的,onSetUpBeforeTransaction、onTearDownAfterTransaction13. 包含? containsWhitespace containsLocalBean14. 存在?有?hasFieldErrors15. 执行 execute16. 回调类中的方法。 doInContext17. 在之后、之前。 Before , after , afterPropertiesSet18. 处理。 RowCallbackHandler 种的processRow19. 预、后处理 preProcess postProcess postBeforeInitializtion20. 21. 提取、解析ResultSetExtractor extractData 、parseData22. 如果可能 createLinkedSetIfPossible23. 刷新或装载refreshLoadorrefreshthepersistentrepresentationoftheconfiguration, *whichmightanXMLfile,propertiesfile,orrelationaldatabaseschema.24. 调用多个类或动作, 要添加s,invokeBeanFactoryPostProcessors25. 注册 registerListeners26. 实例化 preInstantiate27. 预先 pre28. 临时 temp29. 添加、删除、代替,attributeAdded、attributeRemoved、attributeReplaced30. 在操作后处理 postProcessAfterInitialization31. 发布 publishEvent32. 内部的 Internal 。RequestContextAwareTag doStartTagInternal33. 【计】换码 Escape htmlEscape34. 执行脚本 executeSqlScript4.5 常量1Enum方式。例如:propagation2工具类可以定义常量。WebUtils 4.6 异常1. 对于catch到的所有异常,对于实例都可以命名为:excatch (MailException ex) throw ex; 2. 异常的命名完全描述操作的意图CannotGetJdbcConnectionException 、NameNotFoundException4.7 工具类1. 提供一些计算、查询、统计等工具性方法。2. 可以广泛的被其他类进行引用。3. 验证参数类,Spring有自己的Validator 和Errors相互配合使用4. 通常以utils结尾。例如:ValidationUtils、WebApplicationContextUtils5. 4.8 注释1. 对函数的解释,通常是在接口中描述,对于子类要实现时,可以根据具体的情况,添加注释,如果父类,已经表述的非常清楚,子类可以不用添加注释。2. 例如:CommonsMultipartResolver 中的isMultipart、resolveMultipart3. 常用的注释形式 i. Return false by default. ii. Local DataSource that works in any environment iii. A constant indicating that iv. Phone number is required. v. Root WebApplicationContext: initialization completed in4.9 常用英文注释和单词1. e.g. e.g. for updates when comingback from the GUI, is straightforward, as the instance has kept its identity.2. Note that Hibernate works on unmodified plain Java objects, performing dirtydetection via copies made at load time.Note:is same 3. assumably assumably often as anonymous classes within a method implementation.4. if any 即便要 Apply the current transaction timeout, if any, to the givenHibernate Query object5. i.e. Allows for returning a result object created within the callback, i.e.a domain object or a collection of domain objects.6. non-null7. Utility methods for managing versions and timestamps8. Has the following responsibilities:9. / do nothing10. named 指定的4.10 其他1. 5 设计方式5.1 类文件分析LocalVariableTableParameterNameDiscovererParameterNameDiscovererUses ObjectWebs ASM library for analyzing class files.5.2 类委托DelegatingActionUtils5.3 函数委托/* *Performascanwithinthespecifiedbasepackages. *parambasePackagesthepackagestocheckforannotatedclasses *returnnumberofbeansregistered */ publicint scan(String. basePackages) int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); doScan(basePackages); / Register annotation config processors, if necessary. if (this.includeAnnotationConfig) AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); returnthis.registry.getBeanDefinitionCount() - beanCountAtScanStart; 5.4 继承1通常为接口提供了一些默认实现、通用实现。每一个类都有自己的责任。a) ContextLoader b) AbstractContextLoader c) AbstractGenericContextLoader25.5 向JVM注册回调AbstractApplicationContext.registerShutdownHookRegister a shutdown hook with the JVM runtime,5.6 异常后,继续执行SimpleJdbcTestUtils/* * *ExecutethegivenSQLscript. * * *paramsimpleJdbcTemplateTheSimpleJdbcTemplatewithwhichtoperform *JDBCoperations. *paramresourceLoaderTheresourceloader(e.g.,an *link ApplicationContextException)withwhichtoloadtheSQL *script. *paramsqlResourcePathSpringresourcepathfortheSQLscript.Should *normallybeloadedbyclasspath.Thereshouldbeonestatementper *line.Anysemicolonswillberemoved.Donotusethismethodto *executeDDLifyouexpectrollback. *paramcontinueOnErrorwhetherornottocontinuewithoutthrowingan *exceptionintheeventofanerror. *throwsDataAccessExceptionifthereisanerrorexecutingastatement *andcontinueOnErrorwasfalse. */ publicstaticfinalvoid executeSqlScript(final SimpleJdbcTemplate simpleJdbcTemplate, final ResourceLoader resourceLoader, final String sqlResourcePath, finalboolean continueOnError) throws DataAccessException if (logger.isInfoEnabled() (Executing SQL script + sqlResourcePath + ); finallong startTime = System.currentTimeMillis(); final List statements = new LinkedList(); final Resource res = resourceLoader.getResource(sqlResourcePath); try final LineNumberReader lnr = new LineNumberReader(new InputStreamReader(res.getInputStream(); String currentStatement = lnr.readLine(); while (currentStatement != null) currentStatement = StringUtils.replace(currentStatement, ;, ); statements.add(currentStatement); currentStatement = lnr.readLine(); for (final Iterator itr = statements.iterator(); itr.hasNext();) final String statement = itr.next(); try finalint rowsAffected = simpleJdbcTemplate.update(statement); if (logger.isDebugEnabled() logger.debug(rowsAffected + rows affected by SQL: + statement); catch (final DataAccessException ex) if (continueOnError) if (logger.isWarnEnabled() logger.warn(SQL: + statement + failed, ex); else throw ex; finallong elapsedTime = System.currentTimeMillis() - startTime; if (logger.isInfoEnabled() (Done executing SQL script + sqlResourcePath + in + elapsedTime + ms.); catch (final IOException ex) thrownew DataAccessResourceFailureException(Failed to open SQL script + sqlResourcePath + ., ex); 5.7 日志代码1 可以子类方便使用日志工具。/*Loggeravailabletosubclasses*/protectedfinal Log logger = LogFactor
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年职业病防治法试题(含参考答案)
- 电竞赛事品牌传播渠道创新创业项目商业计划书
- 乳清蛋白粉生产创新创业项目商业计划书
- 线上购物线下试驾创新创业项目商业计划书
- 电商平台商品描述服务创新创业项目商业计划书
- 2025年事业单位工勤技能-新疆-新疆机械热加工一级(高级技师)历年参考题库含答案解析(5套)
- 江苏省东海县石榴中学2021届高三上学期9月学情检测数学试题含答案
- 2025年事业单位工勤技能-山西-山西无损探伤工一级(高级技师)历年参考题库含答案解析(5套)
- 2025年事业单位工勤技能-山西-山西城管监察员五级(初级工)历年参考题库含答案解析(5套)
- 2025年事业单位工勤技能-山西-山西地质勘查员二级(技师)历年参考题库含答案解析(5套)
- 产品线库存管理与补货预测系统
- 妇女维权法律知识讲座
- 2025年内蒙古自治区中考语文真题含答案
- 2025版危险货物道路运输综合预案(电石)
- 2025年中医确有专长考试试题及答案
- DB32∕T 4553-2023 医疗机构医疗器械不良事件监测工作指南
- 2025年机关事业单位技能资格考试-政工历年参考题库含答案解析(5套共100道单选合辑)
- 关于工勤人员管理办法
- 传统丧事流程安排方案
- 老中医讲辟谷课件
- 殡葬政策培训课件
评论
0/150
提交评论