亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

direktori cari
前言 簡介 概覽 使用場景 Spring 2.0和 2.5的新特性 簡介 控制反轉(IoC)容器 新的bean作用域 更簡單的XML配置 可擴展的XML編寫 Annotation(注解)驅動配置 在classpath中自動搜索組件 面向切面編程(AOP) 更加簡單的AOP XML配置 對@AspectJ 切面的支持 對bean命名pointcut( bean name pointcut element)的支持 對AspectJ裝載時織入(AspectJ load-time weaving)的支持 中間層 在XML里更為簡單的聲明性事務配置 對Websphere 事務管理的完整支持 JPA 異步的JMS JDBC Web層 Spring MVC合理的默認值 Portlet 框架 基于Annotation的控制器 Spring MVC的表單標簽庫 對Tiles 2 支持 對JSF 1.2支持 JAX-WS支持 其他 動態(tài)語言支持 增強的測試支持 JMX 支持 將Spring 應用程序上下文部署為JCA adapter 計劃任務 對Java 5 (Tiger) 支持 移植到Spring 2.5 改變 支持的JDK版本 Spring 2.5的Jar打包 XML配置 Deprecated(淘汰)的類和方法 Apache OJB iBATIS Hibernate JDO UrlFilenameViewController 更新的樣例應用 改進的文檔 核心技術 IoC(控制反轉)容器 簡介 基本原理 - 容器和bean 容器 配置元數據 實例化容器 XML配置元數據的結構 多種bean bean的命名 bean的別名 實例化bean 用構造器來實例化 使用靜態(tài)工廠方法實例化 使用實例工廠方法實例化 使用容器 依賴 注入依賴 構造器注入 構造器參數解析 構造器參數類型匹配 構造參數索引 Setter注入 一些例子 依賴配置詳解 直接變量(基本類型、Strings類型等。) idref元素 引用其它的bean(協作者) 內部bean 集合 集合的合并 強類型集合(僅適用于Java5+) Nulls XML配置文件的簡寫及其他 XML-based configuration metadata shortcuts 使用p名稱空間配置屬性 組合屬性名稱 使用depends-on 延遲初始化bean 自動裝配(autowire)協作者 將bean排除在自動裝配之外 依賴檢查 方法注入 Lookup方法注入 自定義方法的替代方案 Bean的作用域 Singleton作用域 Prototype作用域 Singleton beans和prototype-bean的依賴 其他作用域 初始化web配置 Request作用域 Session作用域 global session作用域 作用域bean與依賴 選擇創(chuàng)建代理的類型 自定義作用域 創(chuàng)建自定義作用域 使用自定義作用域 定制bean特性 生命周期回調 初始化回調 析構回調 缺省的初始化和析構方法 組合生命周期機制 在非web應用中優(yōu)雅地關閉Spring IoC容器 了解自己 BeanFactoryAware BeanNameAware bean定義的繼承 容器擴展點 用BeanPostProcessor定制bean 使用BeanPostProcessor的Hello World示例 RequiredAnnotationBeanPostProcessor示例 用BeanFactoryPostProcessor定制配置元數據 PropertyPlaceholderConfigurer示例 PropertyOverrideConfigurer示例 使用FactoryBean定制實例化邏輯 The ApplicationContext BeanFactory 還是 ApplicationContext? 利用MessageSource實現國際化 事件 底層資源的訪問 ApplicationContext在WEB應用中的實例化 粘合代碼和可怕的singleton 以J2EE RAR文件的形式部署Spring ApplicationContext 基于注解(Annotation-based)的配置 @Autowired 基于注解的自動連接微調 CustomAutowireConfigurer @Resource @PostConstruct 與 @PreDestroy 對受管組件的Classpath掃描 @Component和更多典型化注解 自動檢測組件 使用過濾器自定義掃描 自動檢測組件的命名 為自動檢測的組件提供一個作用域 用注解提供限定符元數據 注冊一個LoadTimeWeaver 資源 簡介 Resource接口 內置 Resource 實現 UrlResource ClassPathResource FileSystemResource ServletContextResource InputStreamResource ByteArrayResource ResourceLoader接口 ResourceLoaderAware 接口 把Resource作為屬性來配置 Application context 和Resource 路徑 構造application context 創(chuàng)建 ClassPathXmlApplicationContext 實例 - 簡介 Application context構造器中資源路徑的通配符 Ant風格的pattern 潛在的可移植性 classpath*: 前綴 其他關于通配符的說明 FileSystemResource 說明 校驗,數據綁定,BeanWrapper,與屬性編輯器 簡介 使用Spring的Validator接口進行校驗 從錯誤代碼到錯誤信息 Bean處理和BeanWrapper 設置和獲取屬性值以及嵌套屬性 內建的PropertyEditor實現 注冊用戶自定義的PropertyEditor 使用PropertyEditorRegistrars 使用Spring進行面向切面編程(AOP) 簡介 AOP概念 Spring AOP的功能和目標 AOP代理 @AspectJ支持 啟用@AspectJ支持 聲明一個切面 聲明一個切入點(pointcut) 切入點指示符(PCD)的支持 組合切入點表達式 共享通用切入點定義 示例 聲明通知 前置通知 后置通知(After returning advice) 異常通知(After throwing advice) 最終通知(After (finally) advice) 環(huán)繞通知 通知參數(Advice parameters) 訪問當前的連接點 傳遞參數給通知 確定參數名 處理參數 通知順序 引入(Introduction) 切面實例化模型 例子 基于Schema的AOP支持 聲明一個切面 聲明一個切入點 聲明通知 前置通知 后置通知 異常通知 最終通知 環(huán)繞通知 通知參數 通知順序 引入 切面實例化模型 Advisor 例子 AOP聲明風格的選擇 Spring AOP還是完全用AspectJ? Spring AOP中使用@AspectJ還是XML? 混合切面類型 代理機制 理解AOP代理 以編程方式創(chuàng)建@AspectJ代理 在Spring應用中使用AspectJ 在Spring中使用AspectJ進行domain object的依賴注入 @Configurable對象的單元測試 Working with multiple application contexts Spring中其他的AspectJ切面 使用Spring IoC來配置AspectJ的切面 在Spring應用中使用AspectJ加載時織入(LTW) 第一個例子 切面 'META-INF/aop.xml' 相關類庫(JARS) Spring配置 特定環(huán)境的配置 通用Java應用 Tomcat WebLogic 更多資源 Spring AOP APIs 簡介 Spring中的切入點API 概念 切入點運算 AspectJ切入點表達式 便利的切入點實現 靜態(tài)切入點 正則表達式切入點 屬性驅動的切入點 動態(tài)切入點 控制流切入點 切入點的超類 自定義切入點 Spring的通知API 通知的生命周期 Spring里的通知類型 攔截環(huán)繞通知 前置通知 異常通知 后置通知 引入通知 Spring里的Advisor API 使用ProxyFactoryBean創(chuàng)建AOP代理 基礎 JavaBean屬性 基于JDK和CGLIB的代理 對接口進行代理 對類進行代理 使用“全局”通知器 簡化代理定義 使用ProxyFactory通過編程創(chuàng)建AOP代理 操作被通知對象 使用“自動代理(autoproxy)”功能 自動代理bean定義 BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator AbstractAdvisorAutoProxyCreator 使用元數據驅動的自動代理 使用TargetSource 熱交換目標源 池化目標源 原型目標源 ThreadLocal目標源 定義新的Advice類型 更多資源 測試 簡介 單元測試 Mock對象 JNDI Servlet API Portlet API 單元測試支持類 通用工具類 Spring MVC 集成測試 概覽 使用哪個支持框架 通用目標 上下文管理及緩存 測試fixtures依賴注入 事務管理 集成測試支持類 JDBC測試支持 常用注解 JUnit 3.8遺留支持 上下文管理及緩存 測試fixture依賴注入 字段級別(Field Level)注入 事務管理 JUnit 3.8 遺留支持類 Java 5+ 專有支持 使用注解的事務相關測試 JPA支持類 Spring TestContext Framework 主要的抽象 上下文管理和緩存 測試fixture的依賴注入 事務管理 TestContext支持類 JUnit 3.8支持類 JUnit 4.4支持類 定制JUnit 4.4運行器 TestNG支持類 TestContext框架注解支持 PetClinic示例 更多資源 中間層數據訪問 事務管理 簡介 動機 關鍵抽象 使用資源同步的事務 高層次方案 低層次方案 TransactionAwareDataSourceProxy 聲明式事務管理 理解Spring的聲明式事務管理實現 第一個例子 回滾 為不同的bean配置不同的事務語義 <tx:advice/> 有關的設置 使用 @Transactional @Transactional 有關的設置 事務傳播 required RequiresNew Nested 通知事務操作 結合AspectJ使用 @Transactional 編程式事務管理 使用TransactionTemplate 指定事務設置 使用PlatformTransactionManager 選擇編程式事務管理還是聲明式事務管理 與特定應用服務器集成 IBM WebSphere BEA WebLogic Oracle OC4J 常見問題的解決方法 對一個特定的 DataSource 使用了錯誤的事務管理器 更多的資源 DAO支持 簡介 一致的異常層次 一致的DAO支持抽象類 使用JDBC進行數據訪問 簡介 選擇一種工作模式 Spring JDBC包結構 利用JDBC核心類控制JDBC的基本操作和錯誤處理 JdbcTemplate類 一些示例 查詢(SELECT) 更新(INSERT/UPDATE/DELETE) 其他操作 JdbcTemplate 的最佳實踐 NamedParameterJdbcTemplate類 SimpleJdbcTemplate類 DataSource接口 SQLExceptionTranslator接口 執(zhí)行SQL語句 執(zhí)行查詢 更新數據庫 獲取自動生成的主鍵 控制數據庫連接 DataSourceUtils類 SmartDataSource接口 AbstractDataSource類 SingleConnectionDataSource類 DriverManagerDataSource類 TransactionAwareDataSourceProxy類 DataSourceTransactionManager類 NativeJdbcExtractor JDBC批量操作 使用JdbcTemplate進行批量操作 使用SimpleJdbcTemplate進行批量操作 通過使用SimpleJdbc類簡化JDBC操作 使用SimpleJdbcInsert插入數據 使用SimpleJdbcInsert來獲取自動生成的主鍵 指定SimpleJdbcInsert所使用的字段 使用SqlParameterSource提供參數值 使用SimpleJdbcCall調用存儲過程 聲明SimpleJdbcCall使用的參數 如何定義SqlParameters 使用SimpleJdbcCall調用內置函數 使用SimpleJdbcCall返回的ResultSet/REF Cursor 用Java對象來表達JDBC操作 SqlQuery類 MappingSqlQuery類 SqlUpdate類 StoredProcedure類 SqlFunction類 參數和數據處理的基本原則 為參數設置SQL類型信息 處理BLOB 和 CLOB對象 在IN語句中傳入一組參數值 處理復雜類型的存儲過程調用 使用ORM工具進行數據訪問 簡介 Hibernate 資源管理 在Spring容器中創(chuàng)建 SessionFactory The HibernateTemplate 不使用回調的基于Spring的DAO實現 基于Hibernate3的原生API實現DAO 編程式的事務劃分 聲明式的事務劃分 事務管理策略 容器資源 vs 本地資源 在應用服務器中使用Hibernate的注意事項 JDO 建立PersistenceManagerFactory JdoTemplate和JdoDaoSupport 基于原生的JDO API實現DAO 事務管理 JdoDialect Oracle TopLink SessionFactory 抽象層 TopLinkTemplate and TopLinkDaoSupport 基于原生的TopLink API的DAO實現 事務管理 iBATIS SQL Maps 創(chuàng)建SqlMapClient 使用 SqlMapClientTemplate 和 SqlMapClientDaoSupport 基于原生的iBATIS API的DAO實現 JPA 在Spring環(huán)境中建立JPA LocalEntityManagerFactoryBean 從JNDI中獲取 EntityManagerFactory LocalContainerEntityManagerFactoryBean Tomcat(5.0以上)加載時的織入配置 使用VM代理的全局加載時織入 上下文范圍內的加載時織入配置 處理多持久化單元 JpaTemplate 和 JpaDaoSupport 基于原生的JPA實現DAO 異常轉化 事務管理 JpaDialect The Web Web MVC framework Web框架 概述 與其他MVC實現框架的集成 Spring Web MVC框架的特點 DispatcherServlet 控制器 AbstractController 和 WebContentGenerator 其它的簡單控制器 MultiActionController 命令控制器 處理器映射(handler mapping) BeanNameUrlHandlerMapping SimpleUrlHandlerMapping 攔截器(HandlerInterceptor) 視圖與視圖解析 視圖解析器(ViewResolver) 視圖解析鏈 重定向(Rediret)到另一個視圖 RedirectView redirect:前綴 forward:前綴 本地化解析器 AcceptHeaderLocaleResolver CookieLocaleResolver SessionLocaleResolver LocaleChangeInterceptor 使用主題 簡介 如何定義主題 主題解析器 Spring對分段文件上傳(multipart file upload)的支持 介紹 使用MultipartResolver 在表單中處理分段文件上傳 使用Spring的表單標簽庫 配置 form標簽 input標簽 checkbox標簽 checkboxes標簽 radiobutton標簽 radiobuttons標簽 password標簽 select標簽 option標簽 options標簽 textarea標簽 hidden標簽 errors標簽 處理異常 慣例優(yōu)先原則(convention over configuration) 對控制器的支持:ControllerClassNameHandlerMapping 對模型的支持:ModelMap(ModelAndView) 對視圖的支持:RequestToViewNameTranslator 基于注解的控制器配置 建立dispatcher實現注解支持 使用@Controller定義一個控制器 使用@RequestMapping映射請求 使用@RequestParam綁定請求參數到方法參數 使用@ModelAttribute提供一個從模型到數據的鏈接 使用@SessionAttributes指定存儲在會話中的屬性 自定義WebDataBinder初始化 使用@InitBinder自定義數據綁定 配置一個定制的WebBindingInitializer 更多資源 集成視圖技術 簡介 JSP和JSTL 視圖解析器 'Plain-old' JSPs versus JSTL 'Plain-old' JSP與JSTL 幫助簡化開發(fā)的額外的標簽 Tiles 需要的資源 如何集成Tiles UrlBasedViewResolver類 ResourceBundleViewResolver類 SimpleSpringPreparerFactory 和 SpringBeanPreparerFactory Velocity和FreeMarker 需要的資源 Context 配置 創(chuàng)建模板 高級配置 velocity.properties FreeMarker 綁定支持和表單處理 用于綁定的宏 簡單綁定 表單輸入生成宏 輸入域 選擇輸入域 重載HTML轉碼行為并使你的標簽符合XHTML XSLT 寫在段首 Bean 定義 標準MVC控制器代碼 把模型數據轉化為XML 定義視圖屬性 文檔轉換 小結 文檔視圖(PDF/Excel) 簡介 配置和安裝 文檔視圖定義 Controller 代碼 Excel視圖子類 PDF視圖子類 JasperReports 依賴的資源 配置 配置ViewResolver 配置View 關于報表文件 使用 JasperReportsMultiFormatView 構造ModelAndView 使用子報表 配置子報表文件 配置子報表數據源 配置Exporter的參數 集成其它Web框架 簡介 通用配置 JavaServer Faces DelegatingVariableResolver FacesContextUtils Struts ContextLoaderPlugin DelegatingRequestProcessor DelegatingActionProxy ActionSupport Classes Tapestry 注入 Spring 托管的 beans 將 Spring Beans 注入到 Tapestry 頁面中 組件定義文件 添加抽象訪問方法 將 Spring Beans 注入到 Tapestry 頁面中 - Tapestry 4.0+ 風格 WebWork 更多資源 Portlet MVC框架 介紹 控制器 - MVC中的C 視圖 - MVC中的V Web作用范圍的Bean DispatcherPortlet ViewRendererServlet 控制器 AbstractController 和 PortletContentGenerator 其它簡單的控制器 Command控制器 PortletWrappingController 處理器映射 PortletModeHandlerMapping ParameterHandlerMapping PortletModeParameterHandlerMapping 增加 HandlerInterceptors HandlerInterceptorAdapter ParameterMappingInterceptor 視圖和它們的解析 Multipart文件上傳支持 使用 PortletMultipartResolver 處理表單里的文件上傳 異常處理 Portlet應用的部署 整合 使用Spring進行遠程訪問與Web服務 簡介 使用RMI暴露服務 使用RmiServiceExporter暴露服務 在客戶端鏈接服務 使用Hessian或者Burlap通過HTTP遠程調用服務 為Hessian和co.配置DispatcherServlet 使用HessianServiceExporter暴露你的bean 在客戶端連接服務 使用Burlap 對通過Hessian或Burlap暴露的服務使用HTTP Basic認證 使用HTTP調用器暴露服務 Exposing the service object 在客戶端連接服務 Web Services 使用JAX-RPC暴露基于servlet的web服務 使用JAX-RPC訪問web服務 注冊JAX-RPC Bean映射 注冊自己的JAX-RPC 處理器 使用JAX-WS暴露基于servlet的web服務 使用JAX-WS暴露單獨web服務 使用Spring支持的JAX-WS RI來暴露服務 使用JAX-WS訪問web服務 使用XFire來暴露Web服務 JMS 服務端配置 客戶端配置 對遠程接口不提供自動探測實現 在選擇這些技術時的一些考慮 Enterprise Java Beans (EJB) 集成 簡介 訪問EJB 概念 訪問本地的無狀態(tài)Session Bean(SLSB) 訪問遠程SLSB Accessing EJB 2.x SLSBs versus EJB 3 SLSBs 使用Spring提供的輔助類實現EJB組件 EJB 2.x base classes EJB 3 注入攔截 JMS (Java Message Service) 簡介 使用Spring JMS JmsTemplate 連接工廠 目的地管理 消息偵聽容器 SimpleMessageListenerContainer DefaultMessageListenerContainer ServerSessionMessageListenerContainer 事務管理 發(fā)送消息 使用消息轉換器 SessionCallback 和 ProducerCallback 接收消息 同步接收 異步接收 - 消息驅動的POJO SessionAwareMessageListener接口 MessageListenerAdapter 事務中的消息處理 JCA消息端點的支持 JMS命名空間支持 JMX 介紹 將Bean暴露為JMX 創(chuàng)建MBeanServer 重用原有的MBeanServer 延遲初始化的MBean MBean的自動注冊 控制注冊行為 控制Bean的管理接口 MBeanInfoAssembler接口 使用源碼級元數據 使用JDK 5.0的注解 源代碼級的元數據類型 AutodetectCapableMBeanInfoAssembler接口 用Java接口定義管理接口 使用MethodNameBasedMBeanInfoAssembler 控制Bean的ObjectName 從Properties讀取Properties 使用MetadataNamingStrategy <context:mbean-export/>元素 JSR-160連接器 服務器端連接器 客戶端連接器 基于Burlap/Hessian/SOAP的JMX 通過代理訪問MBean 通知 為通知注冊監(jiān)聽器 發(fā)布通知 更多資源 JCA CCI 簡介 配置CCI 連接器配置 在Spring中配置ConnectionFactory 配置CCI連接 使用一個 CCI 單連接 使用Spring的 CCI訪問支持 記錄轉換 CciTemplate類 DAO支持 自動輸出記錄生成 總結 直接使用一個CCI Connection接口和Interaction接口 CciTemplate 使用示例 建模CCI訪問為操作對象 MappingRecordOperation MappingCommAreaOperation 自動生成輸出記錄 總結 MappingRecordOperation 使用示例 MappingCommAreaOperation 使用示例 事務 Spring郵件抽象層 簡介 使用Spring郵件抽象 MailSender 和 SimpleMailMessage 的基本用法 使用 JavaMailSender 和 MimeMessagePreparator 使用MimeMessageHelper 發(fā)送附件和嵌入式資源(inline resources) 附件 內嵌資源 使用模板來創(chuàng)建郵件內容 一個基于Velocity的示例 Spring中的定時調度(Scheduling)和線程池(Thread Pooling) 簡介 使用OpenSymphony Quartz 調度器 使用JobDetailBean 使用 MethodInvokingJobDetailFactoryBean 使用triggers和SchedulerFactoryBean來包裝任務 使用JDK Timer支持類 創(chuàng)建定制的timers 使用 MethodInvokingTimerTaskFactoryBean類 最后:使用TimerFactoryBean來設置任務 SpringTaskExecutor抽象 TaskExecutor接口 TaskExecutor類型 使用TaskExecutor 動態(tài)語言支持 介紹 第一個示例 定義動態(tài)語言支持的bean 公共概念 <lang:language/> 元素 Refreshable bean 內置動態(tài)語言源文件 理解dynamic-language-backed bean上下文中的構造器注入 JRuby beans Groovy beans 通過回調定制Groovy對象 BeanShell beans 場景 Spring MVC控制器的腳本化 Validator的腳本化 Bits and bobs AOP - 通知腳本化bean 作用域 更多的資源 注解和源代碼級的元數據支持 簡介 Spring的元數據支持 注解 @Required Spring中的其它@Annotations Jakarta Commons Attributes集成 元數據和Spring AOP自動代理 基本原理 聲明式事務管理 示例程序 演示案例 介紹 使用動態(tài)語言實現的Spring MVC控制器 構建與部署 使用SimpleJdbcTemplate和@Repository實現DAO 域對象 Data Access Object 構建 XML Schema-based configuration Introduction XML Schema-based configuration Referencing the schemas The util schema <util:constant/> Setting a bean property or constructor arg from a field value <util:property-path/> Using <util:property-path/> to set a bean property or constructor-argument <util:properties/> <util:list/> <util:map/> <util:set/> The jee schema <jee:jndi-lookup/> (simple) <jee:jndi-lookup/> (with single JNDI environment setting) <jee:jndi-lookup/> (with multiple JNDI environment settings) <jee:jndi-lookup/> (complex) <jee:local-slsb/> (simple) <jee:local-slsb/> (complex) <jee:remote-slsb/> The lang schema The jms schema The tx (transaction) schema The aop schema The context schema <property-placeholder/> <annotation-config/> <component-scan/> <load-time-weaver/> <spring-configured/> <mbean-export/> The tool schema The beans schema Setting up your IDE Setting up Eclipse Setting up IntelliJ IDEA Integration issues XML parsing errors in the Resin v.3 application server Extensible XML authoring Introduction Authoring the schema Coding a NamespaceHandler Coding a BeanDefinitionParser Registering the handler and the schema 'META-INF/spring.handlers' 'META-INF/spring.schemas' Using a custom extension in your Spring XML configuration Meatier examples Nesting custom tags within custom tags Custom attributes on 'normal' elements Further Resources spring-beans-2.0.dtd spring.tld Introduction The bind tag The escapeBody tag The hasBindErrors tag The htmlEscape tag The message tag The nestedPath tag The theme tag The transform tag spring-form.tld Introduction The checkbox tag The checkboxes tag The errors tag The form tag The hidden tag The input tag The label tag The option tag The options tag The password tag The radiobutton tag The radiobuttons tag The select tag The textarea tag Spring 2.5開發(fā)手冊中文化項目 聲明 致謝 參與人員 項目歷程
watak

3.5.?定制bean特性

3.5.1.?生命周期回調

Spring提供了幾個標志接口(marker interface),這些接口用來改變容器中bean的行為;它們包括InitializingBeanDisposableBean。實現這兩個接口的bean在初始化和析構時容器會調用前者的afterPropertiesSet()方法,以及后者的destroy()方法。

Spring在內部使用BeanPostProcessor實現來處理它能找到的任何標志接口并調用相應的方法。如果你需要自定義特性或者生命周期行為,你可以實現自己的 BeanPostProcessor。關于這方面更多的內容可以看第?3.7?節(jié) “容器擴展點”。

下面講述了幾個生命周期標志接口。在附錄中會提供相關的示意圖來展示Spring如何管理bean,以及生命周期特性如何改變bean的內在特性。

3.5.1.1.?初始化回調

實現org.springframework.beans.factory.InitializingBean接口允許容器在設置好bean的所有必要屬性后,執(zhí)行初始化事宜。InitializingBean接口僅指定了一個方法:

void afterPropertiesSet() throws Exception;

通常,要避免使用InitializingBean接口并且不鼓勵使用該接口,因為這樣會將代碼和Spring耦合起來,有一個可選的方案是,可以在Bean定義中指定一個普通的初始化方法,然后在XML配置文件中通過指定init-method屬性來完成。如下面的定義所示:

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
    
    public void init() {
        // do some initialization work
    }
}

...效果與下面完全一樣...

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
    
    public void afterPropertiesSet() {
        // do some initialization work
    }
}

... 但是沒有將代碼與Spring耦合在一起。

3.5.1.2.?析構回調

實現org.springframework.beans.factory.DisposableBean接口的bean允許在容器銷毀該bean的時候獲得一次回調。DisposableBean接口也只規(guī)定了一個方法:

void destroy() throws Exception;

通常,要避免使用DisposableBean標志接口而且不鼓勵使用該接口,因為這樣會將代碼與Spring耦合在一起,有一個可選的方案是,在bean定義中指定一個普通的析構方法,然后在XML配置文件中通過指定destroy-method屬性來完成。如下面的定義所示:

<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }
}

...效果與下面完全一樣...

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {

    public void destroy() {
        // do some destruction work (like releasing pooled connections)
    }
}

... 但是沒有將代碼與Spring耦合在一起。

3.5.1.3.?缺省的初始化和析構方法

如果有人沒有采用Spring所指定的InitializingBeanDisposableBean回調接口來編寫初始化和析構方法回調,會發(fā)現自己正在編寫的方法,其名稱莫過于init(), initialize()dispose()等等。這種生命周期回調方法的名稱最好在一個項目范圍內標準化,這樣團隊中的開發(fā)人員就可以使用同樣的方法名稱,并且確保了某種程度的一致性。

Spring容器通過配置可以實現對每個 bean初始化時的查找和銷毀時的回調調用。這也就是說,一個應用的開發(fā)者可以借助于初始化的回調方法init() 輕松的寫一個類(不必想XML配置文件那樣為每個bean都配置一個'init-method="init"'屬性)。Spring IoC容器在創(chuàng)建bean的時候調用這個方法 (這和之前描述的標準生命周期回調一致)。

為了完全弄清如何使用該特性,讓我們看一個例子。出于示范的目的,假設一個項目的編碼規(guī)范中約定所有的初始化回調方法都被命名為init()而析構回調方法被命名為destroy()。遵循此規(guī)則寫成的類如下所示:

public class DefaultBlogService implements BlogService {

    private BlogDao blogDao;

    public void setBlogDao(BlogDao blogDao) {
        this.blogDao = blogDao;
    }

    // this is (unsurprisingly) the initialization callback method
    public void init() {
        if (this.blogDao == null) {
            throw new IllegalStateException("The [blogDao] property must be set.");
        }
    }
}
<beans default-init-method="init">

    <bean id="blogService" class="com.foo.DefaultBlogService">
        <property name="blogDao" ref="blogDao" />
    </bean>

</beans>

注意在頂級的<beans/>元素中的'default-init-method'屬性。這個屬性的含義是Spring IoC容器在bean創(chuàng)建和裝配的時候會將'init'方法作為實例化回調方法。如果類有這個方法,則會在適當的時候執(zhí)行。

銷毀回調方法配置是相同的 (XML配置),在頂級的<beans/>元素中使用 'default-destroy-method' 屬性。

使用這個功能可以把你從位每個bean指定初始化和銷毀回調的繁雜工作中解救出來。為了一致性,應該強制性的為初始化和銷毀回調方法采用一致的命名規(guī)則。

當已經存在的類的初始化方法的命名規(guī)則與慣例有差異的時候,你應該始終使用<bean/>元素中的'init-method''destroy-method'屬性(在XML配置中)來覆蓋默認的方式。

最后,請注意Spring容器保證在bean的所有依賴都滿足后立即執(zhí)行配置的初始化回調。這意味著初始化回調在原生bean上調用,這也意味著這個時候任何諸如AOP攔截器之類的將不能被應用。一個目標bean是首先完全創(chuàng)建,然后才應用諸如AOP代理等攔截器鏈。注意,如果目標bean和代理是分開定義了,你的代碼甚至可以繞開代理直接和原生bean通信。因此,在初始化方法上使用攔截器將產生未知的結果,因為這將目標bean和它的代理/攔截器的生命周期綁定并且留下了和初始bean直接通信這樣奇怪的方式。

3.5.1.4.?組合生命周期機制

As of Spring 2.5, there are three options for controlling bean lifecycle behavior: the InitializingBean and DisposableBean callback interfaces; custom init() and destroy() methods; and the @PostConstruct and @PreDestroy annotations.

在Spring2.5中有三種方式可以控制bean的生命周期行為: InitializingBeanDisposableBean 回調接口;自定義init()destroy() 方法; @PostConstruct@PreDestroy annotations.

當組合不同的生命周期機制時 - 例如,類層次中使用了不同的生命周期機制 - 開發(fā)者必須注意這些機制的應用順序,下面是初始化方法中的順序:

  • @PostConstruct元注釋

  • InitializingBeanafterPropertiesSet()定義

  • 自定義init()方法配置

析構方法調用順序是相同的:

  • @PreDestroy元注釋

  • DisposableBeandestroy()定義

  • 自定義destroy()方法

注意

如果bean存在多種的生命周期機制配置并且每種機制都配置為不同的方法名, 那所有配置的方法將會按照上面的順利執(zhí)行。然而如果配置了相同的方法名 - 例如, init()初始化方法 - 采用多種機制配置后,只會執(zhí)行一次。

3.5.1.5.?在非web應用中優(yōu)雅地關閉Spring IoC容器

注意

在基于web的ApplicationContext實現中已有相應的代碼來處理關閉web應用時如何恰當地關閉Spring IoC容器。

如果你正在一個非web應用的環(huán)境下使用Spring的IoC容器,例如在桌面富客戶端環(huán)境下,你想讓容器優(yōu)雅的關閉,并調用singleton bean上的相應析構回調方法,你需要在JVM里注冊一個“關閉鉤子”(shutdown hook)。這一點非常容易做到,并且將會確保你的Spring IoC容器被恰當關閉,以及所有由單例持有的資源都會被釋放(當然,為你的單例配置銷毀回調,并正確實現銷毀回調方法,依然是你的工作)。

為了注冊“關閉鉤子”,你只需要簡單地調用在AbstractApplicationContext實現中的registerShutdownHook()方法即可。也就是:

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class Boot {

    public static void main(final String[] args) throws Exception {
        AbstractApplicationContext ctx
            = new ClassPathXmlApplicationContext(new String []{"beans.xml"});

        // add a shutdown hook for the above context... 
        ctx.registerShutdownHook();

        // app runs here...
					// main method exits, hook is called prior to the app shutting down...
    }
}

3.5.2.?了解自己

3.5.2.1.? BeanFactoryAware

對于實現了org.springframework.beans.factory.BeanFactoryAware接口的類,當它被BeanFactory創(chuàng)建后,它會擁有一個指向創(chuàng)建它的BeanFactory的引用。

public interface BeanFactoryAware {

    void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}

這樣bean可以以編程的方式操控創(chuàng)建它們的BeanFactory,當然我們可以將引用的BeanFactory造型(cast)為已知的子類型來獲得更多的功能。它主要用于通過編程來取得BeanFactory所管理的其他bean。雖然在有些場景下這個功能很有用,但是一般來說應該盡量避免使用,因為這樣將使代碼與Spring耦合在一起,而且也有違反轉控制的原則(協作者應該作為屬性提供給bean)。

BeanFactoryAware等效的另一種選擇是使用org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean。不過該方法依然沒有降低與Spring的耦合,但是它并沒有像BeanFactoryAware那樣,違反IoC原則。)

ObjectFactoryCreatingFactoryBeanFactoryBean 的一個實現,它返回一個指向工廠對象的引用,該對象將執(zhí)行bean的查找。ObjectFactoryCreatingFactoryBean類實現了BeanFactoryAware接口;被實際注入到客戶端bean的是ObjectFactory接口的一個實例。這是Spring提供的一個接口(因而依舊沒有完全與Spring解耦),客戶端可以使用ObjectFactorygetObject()方法來查找bean(在其背后,ObjectFactory實例只是簡單的將調用委派給BeanFactory,讓其根據bean的名稱執(zhí)行實際的查找)。你要做的全部事情就是給ObjectFactoryCreatingFactoryBean提供待查找bean的名字。讓我們看一個例子:

package x.y;

public class NewsFeed {
    
    private String news;

    public void setNews(String news) {
        this.news = news;
    }

    public String getNews() {
        return this.toString() + ": '" + news + "'";
    }
}
package x.y;

import org.springframework.beans.factory.ObjectFactory;

public class NewsFeedManager {

    private ObjectFactory factory;

    public void setFactory(ObjectFactory factory) {
        this.factory = factory;
    }

    public void printNews() {
        // here is where the lookup is performed; note that there is no
        // need to hard code the name of the bean that is being looked up...
        NewsFeed news = (NewsFeed) factory.getObject();
        System.out.println(news.getNews());
    }
}

下述是XML配置:

<beans>
    <bean id="newsFeedManager" class="x.y.NewsFeedManager">
        <property name="factory">
            <bean
class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
                <property name="targetBeanName">
                    <idref local="newsFeed" />
                </property>
            </bean>
        </property>
    </bean>
    <bean id="newsFeed" class="x.y.NewsFeed" scope="prototype">
        <property name="news" value="... that's fit to print!" />
    </bean>
</beans>

這里有一個測試用的小程序:在NewsFeedManagerprintNews()方法里,每次針對被注入的ObjectFactory的調用,實際上返回的是一個新的(prototype)newsFeed bean實例。

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.y.NewsFeedManager;

public class Main {

    public static void main(String[] args) throws Exception {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        NewsFeedManager manager = (NewsFeedManager) ctx.getBean("newsFeedManager");
        manager.printNews();
        manager.printNews();
    }
}

上述程序的執(zhí)行輸出如下所示(當然,返回結果會根據你機器的不同而不同)

x.y.NewsFeed@1292d26: '... that's fit to print!'
x.y.NewsFeed@5329c5: '... that's fit to print!'

在Spring2.5中,可以利用BeanFactory的自動裝配作為實現 BeanFactoryAware接口的可選方式。 "傳統(tǒng)"的constructorbyType 自動裝配模式(在第?3.3.5?節(jié) “自動裝配(autowire)協作者”中有描述)對無論是構造器參數或setter方法都能提供 BeanFactory類型的 依賴。這有更多的靈活性(包括自動裝配屬性和多參數方法)。如果使用新的基于元注釋的自動裝配特性,只要屬性、 構造器、方法包含有@Autowired元注釋時,BeanFactory將會自動裝配到對應的屬性、構造器、方法中。請參閱第?3.11.1?節(jié) “@Autowired”。

3.5.2.2.? BeanNameAware

如果一個bean實現了org.springframework.beans.factory.BeanNameAware接口,并且部署入BeanFactory, BeanFactory將通過(BeanNameAware)接口來通知這個bean部署在其下的bean來調用這個bean。這個回調方法應該在bean的所有一般屬性被設置后調用,但應該在初始化回調之前,如InitializingBeanafterPropertiesSet方法或者自定義的初始化方法。

Artikel sebelumnya: Artikel seterusnya: