oracle 的 empty_clob() 转换成SQlServer 的怎么转 100结贴%

qq_17071143 2015-03-24 06:35:35
oracle 的 empty_clob() 转换成SQlServer 的怎么转

oracle
// 1.插入一行
String sql1 = "insert into nncredit_article " + "(classoid,title,content,source,remark," + "sort,use_state,record_user, record_create_time,";
sql1 += "record_modify_time,isshow,showimageurl,author,VERIFYSTATE,bytenum )" + " VALUES(" + bean.getClassoid() + "," + "'" + bean.getTitle() + "'," + "empty_clob()," + "'" + bean.getSource() + "'," + "'" + bean.getRemark() + "'," + "" + bean.getSort() + "," + "" + bean.getUser_State() + "," + "'" + bean.getRecord_User() + "',";


...全文
169 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_17071143 2015-03-25
  • 打赏
  • 举报
回复
LongRui888 2015-03-25
  • 打赏
  • 举报
回复
上面看错了: oracle 中有blob类型,但是sql server 没有clob类型,只有 相应的 varchar(max)类型。 一般要写入大量数据,可以通过程序来写。
LongRui888 2015-03-25
  • 打赏
  • 举报
回复
oracle 中有blob类型,但是sql server 没有blob类型,只有 相应的 varbinary类型。
qq_17071143 2015-03-25
  • 打赏
  • 举报
回复
没有对应的 差不多一样的吗
还在加载中灬 2015-03-24
  • 打赏
  • 举报
回复
我了解了下,貌似没有这个对应的函数,我想你可以直接设置为NULL MSSQL和ORACLE更新LOB的方法也不太一样
SQL中的单记录函数 1.ASCII 返回与指定的字符对应的十进制数; SQL> select ascii('A') A,ascii('a') a,ascii('0') zero,ascii(' ') space from dual; A A ZERO SPACE --------- --------- --------- --------- 65 97 48 32 2.CHR 给出整数,返回对应的字符; SQL> select chr(54740) zhao,chr(65) chr65 from dual; ZH C -- - 赵 A 3.CONCAT 连接两个字符串; SQL> select concat('010-','88888888')||'23' 高乾竞电话 from dual; 高乾竞电话 ---------------- 010-8888888823 4.INITCAP 返回字符串并将字符串的第一个字母变为大写; SQL> select initcap('smith') upp from dual; UPP ----- Smith 5.INSTR(C1,C2,I,J) 在一个字符串中搜索指定的字符,返回发现指定的字符的位置; C1 被搜索的字符串 C2 希望搜索的字符串 I 搜索的开始位置,默认为1 J 出现的位置,默认为1 SQL> select instr('oracle traning','ra',1,2) instring from dual; INSTRING --------- 9 6.LENGTH 返回字符串的长度; SQL> select name,length(name),addr,length(addr),sal,length(to_char(sal)) from .nchar_tst; NAME LENGTH(NAME) ADDR LENGTH(ADDR) SAL LENGTH(TO_CHAR(SAL)) ------ ------------ ---------------- ------------ --------- -------------------- 高乾竞 3 北京市海锭区 6 9999.99 7 7.LOWER 返回字符串,并将所有的字符小写 SQL> select lower('AaBbCcDd')AaBbCcDd from dual; AABBCCDD -------- aabbccdd 8.UPPER 返回字符串,并将所有的字符大写 SQL> select upper('AaBbCcDd') upper from dual; UPPER -------- AABBCCDD 9.RPAD和LPAD(粘贴字符) RPAD 在列的右边粘贴字符 LPAD 在列的左边粘贴字符 SQL> select lpad(rpad('gao',10,'*'),17,'*')from dual; LPAD(RPAD('GAO',1 ----------------- *******gao******* 不够字符则用*来填满 10.LTRIM和RTRIM LTRIM 删除左边出现的字符串 RTRIM 删除右边出现的字符串 SQL> select ltrim(rtrim(' gao qian jing ',' '),' ') from dual; LTRIM(RTRIM(' ------------- gao qian jing 11.SUBSTR(string,start,count) 取子字符串,从start开始,取count个 SQL> select substr('13088888888',3,8) from dual; SUBSTR(' -------- 08888888 12.REPLACE('string','s1','s2') string 希望被替换的字符或变量 s1 被替换的字符串 s2 要替换的字符串 SQL> select replace('he love you','he','i') from dual; REPLACE('HELOVEYOU','HE','I') ------------------------------ i love you 13.SOUNDEX 返回一个与给定的字符串读音相同的字符串 SQL> create table table1(xm varchar(8)); SQL> insert into table1 values('weather'); SQL> insert into table1 values('wether'); SQL> insert into table1 values('gao'); SQL> select xm from table1 where soundex(xm)=soundex('weather'); XM -------- weather wether 14.TRIM('s' from 'string') LEADING 剪掉前面的字符 TRAILING 剪掉后面的字符 如果不指定,默认为空格符 15.ABS 返回指定值的绝对值 SQL> select abs(100),abs(-100) from dual; ABS(100) ABS(-100) --------- --------- 100 100 16.ACOS 给出反余弦的值 SQL> select acos(-1) from dual; ACOS(-1) --------- 3.1415927 17.ASIN 给出反正弦的值 SQL> select asin(0.5) from dual; ASIN(0.5) --------- .52359878 18.ATAN 返回一个数字的反正切值 SQL> select atan(1) from dual; ATAN(1) --------- .78539816 19.CEIL 返回大于或等于给出数字的最小整数 SQL> select ceil(3.1415927) from dual; CEIL(3.1415927) --------------- 4 20.COS 返回一个给定数字的余弦 SQL> select cos(-3.1415927) from dual; COS(-3.1415927) --------------- -1 21.COSH 返回一个数字反余弦值 SQL> select cosh(20) from dual; COSH(20) --------- 242582598 22.EXP 返回一个数字e的n次方根 SQL> select exp(2),exp(1) from dual; EXP(2) EXP(1) -------- --------- 7.3890561 2.7182818 23.FLOOR 对给定的数字取整数 SQL> select floor(2345.67) from dual; FLOOR(2345.67) -------------- 2345 24.LN 返回一个数字的对数值 SQL> select ln(1),ln(2),ln(2.7182818) from dual; LN(1) LN(2) LN(2.7182818) --------- --------- ------------- 0 .69314718 .99999999 25.LOG(n1,n2) 返回一个以n1为底n2的对数 SQL> select log(2,1),log(2,4) from dual; LOG(2,1) LOG(2,4) --------- --------- 0 2 26.MOD(n1,n2) 返回一个n1除以n2的余数 SQL> select mod(10,3),mod(3,3),mod(2,3) from dual; MOD(10,3) MOD(3,3) MOD(2,3) --------- --------- --------- 1 0 2 27.POWER 返回n1的n2次方根 SQL> select power(2,10),power(3,3) from dual; POWER(2,10) POWER(3,3) ----------- ---------- 1024 27 28.ROUND和TRUNC 按照指定的精度进行舍入 SQL> select round(55.5),round(-55.4),trunc(55.5),trunc(-55.5) from dual; ROUND(55.5) ROUND(-55.4) TRUNC(55.5) TRUNC(-55.5) ----------- ------------ ----------- ------------ 56 -55 55 -55 29.SIGN 取数字n的符号,大于0返回1,小于0返回-1,等于0返回0 SQL> select sign(123),sign(-100),sign(0) from dual; SIGN(123) SIGN(-100) SIGN(0) --------- ---------- --------- 1 -1 0 30.SIN 返回一个数字的正弦值 SQL> select sin(1.57079) from dual; SIN(1.57079) ------------ 1 31.SIGH 返回双曲正弦的值 SQL> select sin(20),sinh(20) from dual; SIN(20) SINH(20) --------- --------- .91294525 242582598 32.SQRT 返回数字n的根 SQL> select sqrt(64),sqrt(10) from dual; SQRT(64) SQRT(10) --------- --------- 8 3.1622777 33.TAN 返回数字的正切值 SQL> select tan(20),tan(10) from dual; TAN(20) TAN(10) --------- --------- 2.2371609 .64836083 34.TANH 返回数字n的双曲正切值 SQL> select tanh(20),tan(20) from dual; TANH(20) TAN(20) --------- --------- 1 2.2371609 35.TRUNC 按照指定的精度截取一个数 SQL> select trunc(124.1666,-2) trunc1,trunc(124.16666,2) from dual; TRUNC1 TRUNC(124.16666,2) --------- ------------------ 100 124.16 36.ADD_MONTHS 增加或减去月份 SQL> select to_char(add_months(to_date('199912','yyyymm'),2),'yyyymm') from dual; TO_CHA ------ 200002 SQL> select to_char(add_months(to_date('199912','yyyymm'),-2),'yyyymm') from dual; TO_CHA ------ 199910 37.LAST_DAY 返回日期的最后一天 SQL> select to_char(sysdate,'yyyy.mm.dd'),to_char((sysdate)+1,'yyyy.mm.dd') from dual; TO_CHAR(SY TO_CHAR((S ---------- ---------- 2004.05.09 2004.05.10 SQL> select last_day(sysdate) from dual; LAST_DAY(S ---------- 31-5月 -04 38.MONTHS_BETWEEN(date2,date1) 给出date2-date1的月份 SQL> select months_between('19-12月-1999','19-3月-1999') mon_between from dual; MON_BETWEEN ----------- 9 SQL>selectmonths_between(to_date('2000.05.20','yyyy.mm.dd'),to_date('2005.05.20','yyyy.dd')) mon_betw from dual; MON_BETW --------- -60 39.NEW_TIME(date,'this','that') 给出在this时区=other时区的日期和时间 SQL> select to_char(sysdate,'yyyy.mm.dd hh24:mi:ss') bj_time,to_char(new_time 2 (sysdate,'PDT','GMT'),'yyyy.mm.dd hh24:mi:ss') los_angles from dual; BJ_TIME LOS_ANGLES ------------------- ------------------- 2004.05.09 11:05:32 2004.05.09 18:05:32 40.NEXT_DAY(date,'day') 给出日期date和星期x之后计算下一个星期的日期 SQL> select next_day('18-5月-2001','星期五') next_day from dual; NEXT_DAY ---------- 25-5月 -01 41.SYSDATE 用来得到系统的当前日期 SQL> select to_char(sysdate,'dd-mm-yyyy day') from dual; TO_CHAR(SYSDATE,' ----------------- 09-05-2004 星期日 trunc(date,fmt)按照给出的要求将日期截断,如果fmt='mi'表示保留分,截断秒 SQL> select to_char(trunc(sysdate,'hh'),'yyyy.mm.dd hh24:mi:ss') hh, 2 to_char(trunc(sysdate,'mi'),'yyyy.mm.dd hh24:mi:ss') hhmm from dual; HH HHMM ------------------- ------------------- 2004.05.09 11:00:00 2004.05.09 11:17:00 42.CHARTOROWID 将字符数据类型换为ROWID类型 SQL> select rowid,rowidtochar(rowid),ename from scott.emp; ROWID ROWIDTOCHAR(ROWID) ENAME ------------------ ------------------ ---------- AAAAfKAACAAAAEqAAA AAAAfKAACAAAAEqAAA SMITH AAAAfKAACAAAAEqAAB AAAAfKAACAAAAEqAAB ALLEN AAAAfKAACAAAAEqAAC AAAAfKAACAAAAEqAAC WARD AAAAfKAACAAAAEqAAD AAAAfKAACAAAAEqAAD JONES 43.CONVERT(c,dset,sset) 将源字符串 sset从一个语言字符集换到另一个目的dset字符集 SQL> select convert('strutz','we8hp','f7dec') "conversion" from dual; conver ------ strutz 44.HEXTORAW 将一个十六进制构成的字符串换为二进制 45.RAWTOHEXT 将一个二进制构成的字符串换为十六进制 46.ROWIDTOCHAR 将ROWID数据类型换为字符类型 47.TO_CHAR(date,'format') SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') from dual; TO_CHAR(SYSDATE,'YY ------------------- 2004/05/09 21:14:41 48.TO_DATE(string,'format') 将字符串化为ORACLE中的一个日期 49.TO_MULTI_BYTE 将字符串中的单字节字符化为多字节字符 SQL> select to_multi_byte('高') from dual; TO -- 高 50.TO_NUMBER 将给出的字符换为数字 SQL> select to_number('1999') year from dual; YEAR --------- 1999 51.BFILENAME(dir,file) 指定一个外部二进制文件 SQL>insert into file_tb1 values(bfilename('lob_dir1','image1.gif')); 52.CONVERT('x','desc','source') 将x字段或变量的源source换为desc SQL> select sid,serial#,username,decode(command, 2 0,'none', 3 2,'insert', 4 3, 5 'select', 6 6,'update', 7 7,'delete', 8 8,'drop', 9 'other') cmd from v$session where type!='background'; SID SERIAL# USERNAME CMD --------- --------- ------------------------------ ------ 1 1 none 2 1 none 3 1 none 4 1 none 5 1 none 6 1 none 7 1275 none 8 1275 none 9 20 GAO select 10 40 GAO none 53.DUMP(s,fmt,start,length) DUMP函数以fmt指定的内部数字格式返回一个VARCHAR2类型的值 SQL> col global_name for a30 SQL> col dump_string for a50 SQL> set lin 200 SQL> select global_name,dump(global_name,1017,8,5) dump_string from global_name; GLOBAL_NAME DUMP_STRING ------------------------------ -------------------------------------------------- ORACLE.WORLD Typ=1 Len=12 CharacterSet=ZHS16GBK: W,O,R,L,D 54.EMPTY_BLOB()和EMPTY_CLOB() 这两个函数都是用来对大数据类型字段进行初始化操作的函数 55.GREATEST 返回一组表达式中的最大值,即比较字符的编码大小. SQL> select greatest('AA','AB','AC') from dual; GR -- AC SQL> select greatest('啊','安','天') from dual; GR -- 天 56.LEAST 返回一组表达式中的最小值 SQL> select least('啊','安','天') from dual; LE -- 啊 57.UID 返回标识当前用户的唯一整数 SQL> show user USER 为"GAO" SQL> select username,user_id from dba_users where user_id=uid; USERNAME USER_ID ------------------------------ --------- GAO 25 58.USER 返回当前用户的名字 SQL> select user from dual; USER ------------------------------ GAO 59.USEREVN 返回当前用户环境的信息,opt可以是: ENTRYID,SESSIONID,TERMINAL,ISDBA,LABLE,LANGUAGE,CLIENT_INFO,LANG,VSIZE ISDBA 查看当前用户是否是DBA如果是则返回true SQL> select userenv('isdba') from dual; USEREN ------ FALSE SQL> select userenv('isdba') from dual; USEREN ------ TRUE SESSION 返回会话标志 SQL> select userenv('sessionid') from dual; USERENV('SESSIONID') -------------------- 152 ENTRYID 返回会话人口标志 SQL> select userenv('entryid') from dual; USERENV('ENTRYID') ------------------ 0 INSTANCE 返回当前INSTANCE的标志 SQL> select userenv('instance') from dual; USERENV('INSTANCE') ------------------- 1 LANGUAGE 返回当前环境变量 SQL> select userenv('language') from dual; USERENV('LANGUAGE') ---------------------------------------------------- SIMPLIFIED CHINESE_CHINA.ZHS16GBK LANG 返回当前环境的语言的缩写 SQL> select userenv('lang') from dual; USERENV('LANG') ---------------------------------------------------- ZHS TERMINAL 返回用户的终端或机器的标志 SQL> select userenv('terminal') from dual; USERENV('TERMINA ---------------- GAO VSIZE(X) 返回X的大小(字节)数 SQL> select vsize(user),user from dual; VSIZE(USER) USER ----------- ------------------------------ 6 SYSTEM 60.AVG(DISTINCT|ALL) all表示对所有的值求平均值,distinct只对不同的值求平均值 SQLWKS> create table table3(xm varchar(8),sal number(7,2)); 语句已处理。 SQLWKS> insert into table3 values('gao',1111.11); SQLWKS> insert into table3 values('gao',1111.11); SQLWKS> insert into table3 values('zhu',5555.55); SQLWKS> commit; SQL> select avg(distinct sal) from gao.table3; AVG(DISTINCTSAL) ---------------- 3333.33 SQL> select avg(all sal) from gao.table3; AVG(ALLSAL) ----------- 2592.59 61.MAX(DISTINCT|ALL) 求最大值,ALL表示对所有的值求最大值,DISTINCT表示对不同的值求最大值,相同的只取一次 SQL> select max(distinct sal) from scott.emp; MAX(DISTINCTSAL) ---------------- 5000 62.MIN(DISTINCT|ALL) 求最小值,ALL表示对所有的值求最小值,DISTINCT表示对不同的值求最小值,相同的只取一次 SQL> select min(all sal) from gao.table3; MIN(ALLSAL) ----------- 1111.11 63.STDDEV(distinct|all) 求标准差,ALL表示对所有的值求标准差,DISTINCT表示只对不同的值求标准差 SQL> select stddev(sal) from scott.emp; STDDEV(SAL) ----------- 1182.5032 SQL> select stddev(distinct sal) from scott.emp; STDDEV(DISTINCTSAL) ------------------- 1229.951 64.VARIANCE(DISTINCT|ALL) 求协方差 SQL> select variance(sal) from scott.emp; VARIANCE(SAL) ------------- 1398313.9 65.GROUP BY 主要用来对一组数进行统计 SQL> select deptno,count(*),sum(sal) from scott.emp group by deptno; DEPTNO COUNT(*) SUM(SAL) --------- --------- --------- 10 3 8750 20 5 10875 30 6 9400 66.HAVING 对分组统计再加限制条件 SQL> select deptno,count(*),sum(sal) from scott.emp group by deptno having nt(*)>=5; DEPTNO COUNT(*) SUM(SAL) --------- --------- --------- 20 5 10875 30 6 9400 SQL> select deptno,count(*),sum(sal) from scott.emp having count(*)>=5 group by tno ; DEPTNO COUNT(*) SUM(SAL) --------- --------- --------- 20 5 10875 30 6 9400 67.ORDER BY 用于对查询到的结果进行排序输出 SQL> select deptno,ename,sal from scott.emp order by deptno,sal desc; DEPTNO ENAME SAL --------- ---------- --------- 10 KING 5000 10 CLARK 2450 10 MILLER 1300 20 SCOTT 3000 20 FORD 3000 20 JONES 2975 20 ADAMS 1100 20 SMITH 800 30 BLAKE 2850 30 ALLEN 1600 30 TURNER 1500 30 WARD 1250 30 MARTIN 1250 30 JAMES 950
3.70.0.18 15-Jun-11 Possibility to load data in TVirtualTable without recreating persistent fields is added Working in design time editor of the TVirtualTable component is improved Loading files opened by other applications is improved Bug with the "BAD HANDSHAKE" error on connecting to some versions of MySQL server in the MySQL provider is fixed Bug with processing key fields on record posting is fixed Bug with empty string parameters is fixed for ASE data provider Bug with DateTime parameter is fixed for ASE data provider Bug with "SQL statement doesn't return rows" is fixed for ASE data provider Several bugs with design-time editors for Lazarus are fixed 3.70.0.17 28-Apr-11 Lazarus 0.9.30 and FPC 2.4.2 is supported New DBF provider is added Bug in bookmark validity check is fixed Oracle data provider Oracle 9, Oracle 10, and Oracle 11 authentication in the Direct mode is supported Case sensitive login and password in the Direct mode is supported Unicode login and password in the Direct mode is supported Client Identifier in the Direct mode is supported Support of BLOB, CLOB, and NCLOB data types in TUniLoader is improved PostgreSQL data provider Application Name connection option is supported Payload parameter for PostgreSQL notification is supported SQL Server data provider Support for SQL Server Compact Edition 4.0 is added SQLite data provider User-defined function for SQLite provider is supported Default UniNoCase collation for SQLite provider is added (the DefaultCollations specific option) Interface user-defined collation registration for SQLite provider is improved SQLite source version is fixed (missing .inc file is added) Bug with "SQLite function is not linked" in the SQLite data provider is fixed Adaptive Server Enterprise data provider Support for the AnsiNull option in the ASE provider is added Bug with getting extended fields info in a transaction in the ASE data provider is fixed
Struts+Spring+Hibernate实现上传下载      本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。SSH各框架的均为当前最新版本:   •Struts 1.2   •Spring 1.2.5   •Hibernate 3.0   本文选用的数据库为Oracle 9i,当然你可以在不改动代码的情况下,通过配置文件的调整将其移植到任何具有Blob字段类型的数据库上,如MySQL,SQLServer等。   总体实现   上传文件保存到T_FILE表中,T_FILE表结构如下: 图 1 T_FILE表结构   其中:   •FILE_ID:文件ID,32个字符,用Hibernate的uuid.hex算法生成。   •FILE_NAME:文件名。   •FILE_CONTENT:文件内容,对应Oracle的Blob类型。   •REMARK:文件备注。   文件数据存储在Blob类型的FILE_CONTENT表字段上,在Spring中采用OracleLobHandler来处理Lob字段(包括Clob和Blob),由于在程序中不需要引用到oracle数据驱动程序的具体类且屏蔽了不同数据库处理Lob字段方法上的差别,从而撤除程序在多数据库移植上的樊篱。   1.首先数据表中的Blob字段在Java领域对象中声明为byte[]类型,而非java.sql.Blob类型。   2.数据表Blob字段在Hibernate持久化映射文件中的type为org.springframework.orm.hibernate3.support.BlobByteArrayType,即Spring所提供的用户自定义的类型,而非java.sql.Blob。 3在Spring中使用org.springframework.jdbc.support.lob.OracleLobHandler处理Oracle数据库的Blob类型字段。   通过这样的设置和配置,我们就可以象持久化表的一般字段类型一样处理Blob字段了。   以上是Spring+Hibernate将文件二进制数据持久化到数据库的解决方案,而Struts通过将表单中file类型的组件映射为ActionForm中类型为org.apache.struts.upload. FormFile的属性来获取表单提交的文件数据。   工程的类按SSH的层次结构划分为数据持久层、业务层和Web层;WEB-INF下的applicationContext.xml为Spring的配置文件,struts-config.xml为Struts的配置文件,file-upload.jsp为文件上传页面,file-list.jsp为文件列表页面。   本文后面的章节将从数据持久层->业务层->Web层的开发顺序,逐层讲解文件上传下载的开发过程。   数据持久层   1、领域对象及映射文件   您可以使用Hibernate Middlegen、HIbernate Tools、Hibernate Syhchronizer等工具或手工的方式,编写Hibernate的领域对象和映射文件。其中对应T_FILE表的领域对象Tfile.java为:   代码 1 领域对象Tfile 1. package sshfile.model; 2. public class Tfile 3.{ 4. private String fileId; 5. private String fileName; 6. private byte[] fileContent; 7. private String remark; 8. …//getter and setter 9. }   特别需要注意的是:数据库表为Blob类型的字段在Tfile中的fileContent类型为byte[]。Tfile的Hibernate映射文件Tfile.hbm.xml放在Tfile .java类文件的相同目录下:   代码 2 领域对象映射文件 1. <?xml version="1.0"?> 2. <!DOCTYPE hibernate-mapping PUBLIC 3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 5. <hibernate-mapping> 6. <class name="sshfile.model.Tfile" table="T_FILE"> 7. <id name="fileId" type="java.lang.String" column="FILE_ID"> 8. <generator class="uuid.hex"/> 9. </id> 10. <property name="fileContent" 11. type="org.springframework.orm.hibernate3.support.BlobByteArrayType" 12. column="FILE_CONTENT" lazy="true"/> 13. …//其它一般字段的映射 14. </class> 15. </hibernate-mapping>   fileContent字段映射为Spring所提供的BlobByteArrayType类型,BlobByteArrayType是用户自定义的数据类型,它实现了Hibernate 的org.hibernate.usertype.UserType接口。BlobByteArrayType使用从sessionFactory获取的Lob操作句柄lobHandler将byte[]的数据保存到Blob数据库字段中。这样,我们就再没有必要通过硬编码的方式,先insert然后再update来完成Blob类型数据的持久化,这个原来难伺候的老爷终于被平民化了。关于lobHandler的配置请见本文后面的内容。   此外lazy="true"说明地返回整个Tfile对象时,并不返回fileContent这个字段的数据,只有在显式调用tfile.getFileContent()方法时才真正从数据库中获取fileContent的数据。这是Hibernate3引入的新特性,对于包含重量级大数据的表字段,这种抽取方式提高了对大字段操作的灵活性,否则加载Tfile对象的结果集时如果总是返回fileContent,这种批量的数据抽取将可以引起数据库的"洪泛效应"。   2、DAO编写和配置   Spring强调面向接口编程,所以我们将所有对Tfile的数据操作的方法定义在TfileDAO接口中,这些接口方法分别是:   •findByFildId(String fileId)   •save(Tfile tfile)   •List findAll()   TfileDAOHibernate提供了对TfileDAO接口基于Hibernate的实现,如代码 3所示:   代码 3 基于Hibernate 的fileDAO实现类 1. package sshfile.dao; 2. 3. import sshfile.model.*; 4. import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 5. import java.util.List; 6. 7. public class TfileDAOHibernate 8. extends HibernateDaoSupport implements TfileDAO 9. { 10. public Tfile findByFildId(String fileId) 11. { 12. return (Tfile) getHibernateTemplate().get(Tfile.class, fileId); 13. } 14. public void save(Tfile tfile) 15. { 16. getHibernateTemplate().save(tfile); 17. getHibernateTemplate().flush(); 18. } 19. public List findAll() 20. { 21. return getHibernateTemplate().loadAll(Tfile.class); 22. } 23. }   TfileDAOHibernate通过扩展Spring提供的Hibernate支持类HibernateDaoSupport而建立,HibernateDaoSupport封装了HibernateTemplate,而HibernateTemplate封装了Hibernate所提供几乎所有的的数据操作方法,如execute(HibernateCallback action),load(Class entityClass, Serializable id),save(final Object entity)等等。   所以我们的DAO只需要简单地调用父类的HibernateTemplate就可以完成几乎所有的数据库操作了。   由于Spring通过代理Hibernate完成数据层的操作,所以原Hibernate的配置文件hibernate.cfg.xml的信息也移到Spring的配置文件中:   代码 4 Spring中有关Hibernate的配置信息 1. <beans> 2. <!-- 数据源的配置 //--> 3. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 4. destroy-method="close"> 5. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> 6. <property name="url" value="jdbc:oracle:thin:@localhost:1521:ora9i"/> 7. <property name="username" value="test"/> 8. <property name="password" value="test"/> 9. </bean> 10. <!-- Hibernate会话工厂配置 //--> 11. <bean id="sessionFactory" 12. class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 13. <property name="dataSource" ref="dataSource"/> 14. <property name="mappingDirectoryLocations"> 15. <list> 16. <value>classpath:/sshfile/model</value> 17. </list> 18. </property> 19. <property name="hibernateProperties"> 20. <props> 21. <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> 22. <prop key="hibernate.cglib.use_reflection_optimizer">true</prop> 23. </props> 24. </property> 25. </bean> 26. <!-- Hibernate 模板//--> 27. <bean id="hibernateTemplate" 28. class="org.springframework.orm.hibernate3.HibernateTemplate"> 29. <property name="sessionFactory" ref="sessionFactory"/> 30. </bean> 31. <!--DAO配置 //--> 32. <bean id="tfileDAO" class="sshfile.dao.TfileDAOHibernate"> 33. <property name="hibernateTemplate" ref="hibernateTemplate" /> 34. </bean> 35. … 36. </beans>   第3~9行定义了一个数据源,其实现类是apache的BasicDataSource,第11~25行定义了Hibernate的会话工厂,会话工厂类用Spring提供的LocalSessionFactoryBean维护,它注入了数据源和资源映射文件,此外还通过一些键值对设置了Hibernate所需的属性。   其中第16行通过类路径的映射方式,将sshfile.model类包目录下的所有领域对象的映射文件装载进来,在本文的例子里,它将装载进Tfile.hbm.xml映射文件。如果有多个映射文件需要声明,使用类路径映射方式显然比直接单独指定映射文件名的方式要简便。   第27~30行定义了Spring代理Hibernate数据操作的HibernateTemplate模板,而第32~34行将该模板注入到tfileDAO中。   需要指定的是Spring 1.2.5提供了两套Hibernate的支持包,其中Hibernate 2相关的封装类位于org.springframework.orm.hibernate2.*包中,而Hibernate 3.0的封装类位于org.springframework.orm.hibernate3.*包中,需要根据您所选用Hibernate版本进行正确选择。   3、Lob字段处理的配置   我们前面已经指出Oracle的Lob字段和一般类型的字段在操作上有一个明显的区别--那就是你必须首先通过Oracle的empty_blob()/empty_clob()初始化Lob字段,然后获取该字段的引用,通过这个引用更改其值。所以要完成对Lob字段的操作,Hibernate必须执行两步数据库访问操作,先Insert再Update。   使用BlobByteArrayType字段类型后,为什么我们就可以象一般的字段类型一样操作Blob字段呢?可以确定的一点是:BlobByteArrayType不可能逾越Blob天生的操作方式,原来是BlobByteArrayType数据类型本身具体数据访问的功能,它通过LobHandler将两次数据访问的动作隐藏起来,使Blob字段的操作在表现上和其他一般字段业类型无异,所以LobHandler即是那个"苦了我一个,幸福十亿人"的那位幕后英雄。   LobHandler必须注入到Hibernate会话工厂sessionFactory中,因为sessionFactory负责产生与数据库交互的Session。LobHandler的配置如代码 5所示:   代码 5 Lob字段的处理句柄配置 1. <beans> 2. … 3. <bean id="nativeJdbcExtractor" 4. class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" 5. lazy-init="true"/> 6. <bean id="lobHandler" 7. class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true"> 8. <property name="nativeJdbcExtractor"> 9. <ref local="nativeJdbcExtractor"/> 10. </property> 11. </bean> 12. … 13. </beans>   首先,必须定义一个能够从连接池中抽取出本地数据库JDBC对象(如OracleConnection,OracleResultSet等)的抽取器:nativeJdbcExtractor,这样才可以执行一些特定数据库的操作。对于那些仅封装了Connection而未包括Statement的简单数据连接池,SimpleNativeJdbcExtractor是效率最高的抽取器实现类,但具体到apache的BasicDataSource连接池,它封装了所有JDBC的对象,这时就需要使用CommonsDbcpNativeJdbcExtractor了。Spring针对几个著名的Web服务器的数据源提供了相应的JDBC抽取器:   •WebLogic:WebLogicNativeJdbcExtractor   •WebSphere:WebSphereNativeJdbcExtractor   •JBoss:JBossNativeJdbcExtractor   在定义了JDBC抽取器后,再定义lobHandler。Spring 1.2.5提供了两个lobHandler:   •DefaultLobHandler:适用于大部分的数据库,如SqlServer,MySQL,对Oracle 10g也适用,但不适用于Oracle 9i(看来Oracle 9i确实是个怪胎,谁叫Oracle 公司自己都说Oracle 9i是一个过渡性的产品呢)。   •OracleLobHandler:适用于Oracle 9i和Oracle 10g。   由于我们的数据库是Oracle9i,所以使用OracleLobHandler。   在配置完LobHandler后, 还需要将其注入到sessionFactory的Bean中,下面是调用后的sessionFactory Bean的配置:   代码 6 将lobHandler注入到sessionFactory中的配置 1. <beans> 2. … 3. <bean id="sessionFactory" 4. class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 5. <property name="dataSource" ref="dataSource"/> 6. <!-- 为处理Blob类型字段的句柄声明 //--> 7. <property name="lobHandler" ref="lobHandler"/> 8. … 9. </bean> 10. … 11. </beans>   如第7所示,通过sessionFactory的lobHandler属性进行注入。  业务层   1、业务层接口   "面向接口而非面向类编程"是Spring不遗余力所推荐的编程原则,这条原则也已经为大部开发者所接受;此外,JDK的动态代理只对接口有效,否则必须使用CGLIB生成目标类的子类。我们依从于Spring的倡导为业务类定义一个接口:   代码 7 业务层操作接口 1. public interface FileService 2. { 3. void save(FileActionForm fileForm);//将提交的上传文件保存到数据表中 4. List getAllFile();//得到T_FILE所示记录 5. void write(OutputStream os,String fileId);//将某个文件的文件数据写出到输出流中 6. String getFileName(String fileId);//获取文件名 7. }   其中save(FileActionForm fileForm)方法,将封装在fileForm中的上传文件保存到数据库中,这里我们使用FileActionForm作为方法入参,FileActionForm是Web层的表单数据对象,它封装了提交表单的数据。将FileActionForm直接作为业务层的接口入参,相当于将Web层传播到业务层中去,即将业务层绑定在特定的Web层实现技术中,按照分层模型学院派的观点,这是一种反模块化的设计,但在"一般"的业务系统并无需提供多种UI界面,系统Web层将来切换到另一种实现技术的可能性也微乎其微,所以笔者觉得没有必要为了这个业务层完全独立于调用层的过高目标而去搞一个额外的隔离层,浪费了原材料不说,还将系统搞得过于复杂,相比于其它原则,"简单"始终是最大的一条原则。   getAllFile()负责获取T_FILE表所有记录,以便在网页上显示出来。   而getFileName(String fileId)和write(OutputStream os,String fileId)则用于下载某个特定的文件。具体的调用是将Web层将response.getOutputStream()传给write(OutputStream os,String fileId)接口,业务层直接将文件数据输出到这个响应流中。具体实现请参见错误!未找到引用源。节下载文件部分。   2、业务层接口实现类   FileService的实现类为FileServiceImpl,其中save(FileActionForm fileForm)的实现如下所示:   代码 8 业务接口实现类之save() 1. … 2. public class FileServiceImpl 3. implements FileService 4. { 5. private TfileDAO tfileDAO; 6. public void save(FileActionForm fileForm) 7. { 8. Tfile tfile = new Tfile(); 9. try 10. { 11. tfile.setFileContent(fileForm.getFileContent().getFileData()); 12. } 13. catch (FileNotFoundException ex) 14. { 15. throw new RuntimeException(ex); 16. } 17. catch (IOException ex) 18. { 19. throw new RuntimeException(ex); 20. } 21. tfile.setFileName(fileForm.getFileContent().getFileName()); 22. tfile.setRemark(fileForm.getRemark()); 23. tfileDAO.save(tfile); 24. } 25. … 26. }   在save(FileActionForm fileForm)方法里,完成两个步骤:   其一,象在水桶间倒水一样,将FileActionForm对象中的数据倒入到Tfile对象中;   其二,调用TfileDAO保存数据。   需要特别注意的是代码的第11行,FileActionForm的fileContent属性为org.apache.struts.upload.FormFile类型,FormFile提供了一个方便的方法getFileData(),即可获取文件的二进制数据。通过解读FormFile接口实现类DiskFile的原码,我们可能知道FormFile本身并不缓存文件的数据,只有实际调用getFileData()时,才从磁盘文件输入流中获取数据。由于FormFile使用流读取方式获取数据,本身没有缓存文件的所有数据,所以对于上传超大体积的文件,也是没有问题的;但是,由于数据持久层的Tfile使用byte[]来缓存文件的数据,所以并不适合处理超大体积的文件(如100M),对于超大体积的文件,依然需要使用java.sql.Blob类型以常规流操作的方式来处理。   此外,通过FileForm的getFileName()方法就可以获得上传文件的文件名,如第21行代码所示。   write(OutputStream os,String fileId)方法的实现,如代码 9所示:   代码 9 业务接口实现类之write() 1. … 2. public class FileServiceImpl 3. implements FileService 4. { 5. 6. public void write(OutputStream os, String fileId) 7. { 8. Tfile tfile = tfileDAO.findByFildId(fileId); 9. try 10. { 11. os.write(tfile.getFileContent()); 12. os.flush(); 13. } 14. catch (IOException ex) 15. { 16. throw new RuntimeException(ex); 17. } 18. } 19. … 20. }   write(OutputStream os,String fileId)也简单地分为两个操作步骤,首先,根据fileId加载表记录,然后将fileContent写入到输出流中。   3、Spring事务配置   下面,我们来看如何在Spring配置文件中为FileService配置声明性的事务 1. <beans> 2. … 3. <bean id="transactionManager" 4. class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 5. <property name="sessionFactory" ref="sessionFactory"/> 6. </bean> 7. <!-- 事务处理的AOP配置 //--> 8. <bean id="txProxyTemplate" abstract="true" 9. class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 10. <property name="transactionManager" ref="transactionManager"/> 11. <property name="transactionAttributes"> 12. <props> 13. <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> 14. <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> 15. <prop key="save">PROPAGATION_REQUIRED</prop> 16. <prop key="write">PROPAGATION_REQUIRED,readOnly</prop> 17. </props> 18. </property> 19. </bean> 20. <bean id="fileService" parent="txProxyTemplate"> 21. <property name="target"> 22. <bean class="sshfile.service.FileServiceImpl"> 23. <property name="tfileDAO" ref="tfileDAO"/> 24. </bean> 25. </property> 26. </bean> 27. </beans>   Spring的事务配置包括两个部分:   其一,定义事务管理器transactionManager,使用HibernateTransactionManager实现事务管理;   其二,对各个业务接口进行定义,其实txProxyTemplate和fileService是父子节点的关系,本来可以将txProxyTemplate定义的内容合并到fileService中一起定义,由于我们的系统仅有一个业务接口需要定义,所以将其定义的一部分抽象到父节点txProxyTemplate中意义确实不大,但是对于真实的系统,往往拥有为数众多的业务接口需要定义,将这些业务接口定义内容的共同部分抽取到一个父节点中,然后在子节点中通过parent进行关联,就可以大大简化业务接口的配置了。   父节点txProxyTemplate注入了事务管理器,此外还定义了业务接口事务管理的方法(允许通过通配符的方式进行匹配声明,如前两个接口方法),有些接口方法仅对数据进行读操作,而另一些接口方法需要涉及到数据的更改。对于前者,可以通过readOnly标识出来,这样有利于操作性能的提高,需要注意的是由于父类节点定义的Bean仅是子节点配置信息的抽象,并不能具体实现化一个Bean对象,所以需要特别标注为abstract="true",如第8行所示。   fileService作为一个目标类被注入到事务代理器中,而fileService实现类所需要的tfileDAO实例,通过引用3.2节中定义的tfileDAO Bean注入。   Web层实现   1、Web层的构件和交互流程   Web层包括主要3个功能:   •上传文件。   •列出所有已经上传的文件列表,以供点击下载。   •下载文件。   Web层实现构件包括与2个JSP页面,1个ActionForm及一个Action:   •file-upload.jsp:上传文件的页面。   •file-list.jsp:已经上传文件的列表页面。   •FileActionForm:file-upload.jsp页面表单对应的ActionForm。   •FileAction:继承org.apache.struts.actions.DispatchAction的Action,这样这个Action就可以通过一个URL参数区分中响应不同的请求。   Web层的这些构件的交互流程如图 6所示: 图 6 Web层Struts流程图   其中,在执行文件上传的请求时,FileAction在执行文件上传后,forward到loadAllFile出口中,loadAllFile加载数据库中所有已经上传的记录,然后forward到名为fileListPage的出口中,调用file-list.jsp页面显示已经上传的记录。   2、FileAction功能   Struts 1.0的Action有一个弱项:一个Action只能处理一种请求,Struts 1.1中引入了一个DispatchAction,允许通过URL参数指定调用Action中的某个方法,如http://yourwebsite/fileAction.do?method=upload即调用FileAction中的upload方法。通过这种方式,我们就可以将一些相关的请求集中到一个Action当中编写,而没有必要为某个请求操作编写一个Action类。但是参数名是要在struts-config.xml中配置的: 1. <struts-config> 2. <form-beans> 3. <form-bean name="fileActionForm" type="sshfile.web.FileActionForm" /> 4. </form-beans> 5. <action-mappings> 6. <action name="fileActionForm" parameter="method" path="/fileAction" 7. type="sshfile.web.FileAction"> 8. <forward name="fileListPage" path="/file-list.jsp" /> 9. <forward name="loadAllFile" path="/fileAction.do?method=listAllFile" /> 10. </action> 11. </action-mappings> 12. </struts-config>   第6行的parameter="method"指定了承载方法名的参数,第9行中,我们还配置了一个调用FileAction不同方法的Action出口。   FileAction共有3个请求响应的方法,它们分别是:   •upload(…):处理上传文件的请求。   •listAllFile(…):处理加载数据库表中所有记录的请求。   •download(…):处理下载文件的请求。   下面我们分别对这3个请求处理方法进行讲解。   2.1 上传文件   上传文件的请求处理方法非常简单,简之言之,就是从Spring容器中获取业务层处理类FileService,调用其save(FileActionForm form)方法上传文件,如下所示: 1. public class FileAction 2. extends DispatchAction 3. { 4. //将上传文件保存到数据库中 5. public ActionForward upload(ActionMapping mapping, ActionForm form, 6. HttpServletRequest request, 7. HttpServletResponse response) 8. { 9. FileActionForm fileForm = (FileActionForm) form; 10. FileService fileService = getFileService(); 11. fileService.save(fileForm); 12. return mapping.findForward("loadAllFile"); 13. } 14. //从Spring容器中获取FileService对象 15. private FileService getFileService() 16. { 17. ApplicationContext appContext = WebApplicationContextUtils. 18. getWebApplicationContext(this.getServlet().getServletContext()); 19. return (FileService) appContext.getBean("fileService"); 20. } 21. … 22. }   由于FileAction其它两个请求处理方法也需要从Spring容器中获取FileService实例,所以我们特别提供了一个getFileService()方法(第15~21行)。重构的一条原则就是:"发现代码中有重复的表达式,将其提取为一个变量;发现类中有重复的代码段,将其提取为一个方法;发现不同类中有相同的方法,将其提取为一个类"。在真实的系统中,往往拥有多个Action和多个Service类,这时一个比较好的设置思路是,提供一个获取所有Service实现对象的工具类,这样就可以将Spring 的Service配置信息屏蔽在一个类中,否则Service的配置名字散落在程序各处,维护性是很差的。   2.2 列出所有已经上传的文件   listAllFile方法调用Servie层方法加载T_FILE表中所有记录,并将其保存在Request域中,然后forward到列表页面中: 1. public class FileAction 2. extends DispatchAction 3. { 4. … 5. public ActionForward listAllFile(ActionMapping mapping, ActionForm form, 6. HttpServletRequest request, 7. HttpServletResponse response) 8. throws ModuleException 9. { 10. FileService fileService = getFileService(); 11. List fileList = fileService.getAllFile(); 12. request.setAttribute("fileList",fileList); 13. return mapping.findForward("fileListPage"); 14. } 15. }   file-list.jsp页面使用Struts标签展示出保存在Request域中的记录: 1. <%@page contentType="text/html; charset=GBK"%> 2. <%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%> 3. <%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%> 4. <html> 5. <head> 6. <title>file-download</title> 7. </head> 8. <body bgcolor="#ffffff"> 9. <ol> 10. <logic:iterate id="item" name="fileList" scope="request"> 11. <li> 12. <a href='fileAction.do?method=download&fileId= 13. <bean:write name="item"property="fileId"/>'> 14. <bean:write name="item" property="fileName"/> 15. </a> 16. </li> 17. </logic:iterate> 18. </ol> 19. </body> 20. </html>   展现页面的每条记录挂接着一个链接地址,形如:fileAction.do?method=download&fileId=xxx,method参数指定了这个请求由FileAction的download方法来响应,fileId指定了记录的主键。   由于在FileActionForm中,我们定义了fileId的属性,所以在download响应方法中,我们将可以从FileActionForm中取得fileId的值。这里涉及到一个处理多个请求Action所对应的ActionForm的设计问题,由于原来的Action只能对应一个请求,那么原来的ActionForm非常简单,它仅需要将这个请求的参数项作为其属性就可以了,但现在一个Action对应多个请求,每个请求所对应的参数项是不一样的,此时的ActionForm的属性就必须是多请求参数项的并集了。所以,除了文件上传请求所对应的fileContent和remark属性外还包括文件下载的fileId属性: 图 7 FileActionForm   当然这样会造成属性的冗余,比如在文件上传的请求中,只会用到fileContent和remark属性,而在文件下载的请求时,只会使用到fileId属性。但这种冗余是会带来好处的--它使得一个Action可以处理多个请求。   2.3 下载文件   在列表页面中点击一个文件下载,其请求由FileAction的download方法来响应,download方法调用业务层的FileService方法,获取文件数据并写出到response的响应流中。通过合理设置HTTP响应头参数,将响应流在客户端表现为一个下载文件对话框,其代码如下所示:   代码 10 业务接口实现类之download 1. public class FileAction 2. extends DispatchAction 3. { 4. … 5. public ActionForward download(ActionMapping mapping, ActionForm form, 6. HttpServletRequest request, 7. HttpServletResponse response) 8. throws ModuleException 9. { 10. FileActionForm fileForm = (FileActionForm) form; 11. FileService fileService = getFileService(); 12. String fileName = fileService.getFileName(fileForm.getFileId()); 13. try 14. { 15. response.setContentType("application/x-msdownload"); 16. response.setHeader("Content-Disposition", 17. "attachment;" + " filename="+ 18. new String(fileName.getBytes(), "ISO-8859-1")); 19. fileService.write(response.getOutputStream(), fileForm.getFileId()); 20. } 21. catch (Exception e) 22. { 23. throw new ModuleException(e.getMessage()); 24. } 25. return null; 26. } 27. }   第15~18行,设置HTTP响应头,将响应类型设置为application/x-msdownload MIME类型,则响应流在IE中将弹出一个文件下载的对话框,如图 4所示。IE所支持的MIME类型多达26种,您可以通过这个网址查看其他的MIME类型: http://msdn.microsoft.com/workshop/networking/moniker/overview/appendix_a.asp。   如果下载文件的文件名含有中文字符,如果不对其进行硬编码,如第18行所示,客户文件下载对话框中出现的文件名将会发生乱码。 第19行代码获得response的输出流,作为FileServie write(OutputStream os,String fileId)的入参,这样文件的内容将写到response的输出流中。   3、web.xml文件的配置 Spring容器在何时启动呢?我可以在Web容器初始化来执行启动Spring容器的操作,Spring提供了两种方式启动的方法:   •通过org.springframework.web.context .ContextLoaderListener容器监听器,在Web容器初始化时触发初始化Spring容器,在web.xml中通过<listener></listener>对其进行配置。   •通过Servlet org.springframework.web.context.ContextLoaderServlet,将其配置为自动启动的Servlet,在Web容器初始化时,通过这个Servlet启动Spring容器。   在初始化Spring容器之前,必须先初始化log4J的引擎,Spring也提供了容器监听器和自动启动Servlet两种方式对log4J引擎进行初始化:  •org.springframework.web.util .Log4jConfigListener  •org.springframework.web.util.Log4jConfigServlet   下面我们来说明如何配置web.xml启动Spring容器:   代码 11 web.xml中对应Spring的配置内容 1. <web-app> 2. <context-param> 3. <param-name>contextConfigLocation</param-name> 4. <param-value>/WEB-INF/applicationContext.xml</param-value> 5. </context-param> 6. <context-param> 7. <param-name>log4jConfigLocation</param-name> 8. <param-value>/WEB-INF/log4j.properties</param-value> 9. </context-param> 10. <servlet> 11. <servlet-name>log4jInitServlet</servlet-name> 12. <servlet-class>org.springframework.web.util.Log4jConfigServlet</servlet-class> 13. <load-on-startup>1</load-on-startup> 14. </servlet> 15. <servlet> 16. <servlet-name>springInitServlet</servlet-name> 17. <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> 18. <load-on-startup>2</load-on-startup> 19. </servlet> 20. … 21. </web-app>   启动Spring容器时,需要得到两个信息:Spring配置文件的地址和Log4J属性文件,这两上信息分别通过contextConfigLocationWeb和log4jConfigLocation容器参数指定,如果有多个Spring配置文件,则用逗号隔开,如: /WEB-INF/applicationContext_1.xml, /WEB-INF/applicationContext_1.xm2   由于在启动ContextLoaderServlet之前,必须事先初始化Log4J的引擎,所以Log4jConfigServlet必须在ContextLoaderServlet之前启动,这通过<load-on-startup>来指定它们启动的先后顺序。   乱码是开发Web应用程序一个比较老套又常见问题,由于不同Web应用服务器的默认编码是不一样的,为了方便Web应用在不同的Web应用服务器上移植,最好的做法是Web程序自身来处理编码换的工作。经典的作法是在web.xml中配置一个编码换过滤器,Spring就提供了一个编码过滤器类CharacterEncodingFilter,下面,我们为应用配置上这个过滤器: 1. <web-app> 2. … 3. <filter> 4. <filter-name>encodingFilter</filter-name> 5. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 6. <init-param> 7. <param-name>encoding</param-name> 8. <param-value>GBK</param-value> 9. </init-param> 10. </filter> 11. <filter-mapping> 12. <filter-name>encodingFilter</filter-name> 13. <url-pattern>/*</url-pattern> 14. </filter-mapping> 15. … 16. </web-app>   Spring的过滤器类是org.springframework.web.filter.CharacterEncodingFilter,通过encoding参数指定编码换类型为GBK,<filter-mapping>的配置使该过滤器截获所有的请示。   Struts的框架也需要在web.xml中配置,想必读者朋友对Struts的配置都很熟悉,故在此不再提及,请参见本文所提供的源码。   总结   本文通过一个文件上传下载的Web应用,讲解了如何构建基于SSH的Web应用,通过Struts和FormFile,Spring的LobHandler以及Spring为HibernateBlob处理所提供的用户类BlobByteArrayType ,实现上传和下载文件的功能仅需要廖廖数行的代码即告完成。读者只需对程序作稍许的调整,即可处理Clob字段:   •领域对象对应Clob字段的属性声明为String类型;   •映射文件对应Clob字段的属性声明为org.springframework.orm.hibernate3.support.ClobStringType类型。
Not Using Commons Logging ................................................................... 12 Using SLF4J ............................................................................................ 13 Using Log4J ............................................................................................. 14 II. What’s New in Spring Framework 4.x .................................................................................... 16 3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .................................................................. 17 3.2. Removed Deprecated Packages and Methods .................................................... 17 3.3. Java 8 (as well as 6 and 7) ............................................................................... 17 3.4. Java EE 6 and 7 ............................................................................................... 18 3.5. Groovy Bean Definition DSL .............................................................................. 18 3.6. Core Container Improvements ............................................................................ 19 3.7. General Web Improvements ............................................................................... 19 3.8. WebSocket, SockJS, and STOMP Messaging ..................................................... 19 3.9. Testing Improvements ........................................................................................ 20 III. Core Technologies .............................................................................................................. 21 4. The IoC container ........................................................................................................ 22 4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview ............................................................................................ 22 Configuration metadata ..................................................................................... 23 Instantiating a container .................................................................................... 24 Composing XML-based configuration metadata .......................................... 25 Using the container .......................................................................................... 26 4.3. Bean overview ................................................................................................... 27 Naming beans .................................................................................................. 28 Aliasing a bean outside the bean definition ................................................ 28 Instantiating beans ........................................................................................... 29 Instantiation with a constructor .................................................................. 29 Instantiation with a static factory method .................................................... 30 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iii Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ................................................................................................... 32 Dependency injection ....................................................................................... 32 Constructor-based dependency injection .................................................... 32 Setter-based dependency injection ............................................................ 34 Dependency resolution process ................................................................. 35 Examples of dependency injection ............................................................. 36 Dependencies and configuration in detail ........................................................... 38 Straight values (primitives, Strings, and so on) ........................................... 38 References to other beans (collaborators) .................................................. 40 Inner beans .............................................................................................. 41 Collections ............................................................................................... 41 Null and empty string values ..................................................................... 44 XML shortcut with the p-namespace .......................................................... 44 XML shortcut with the c-namespace .......................................................... 46 Compound property names ....................................................................... 46 Using depends-on ............................................................................................ 47 Lazy-initialized beans ....................................................................................... 47 Autowiring collaborators .................................................................................... 48 Limitations and disadvantages of autowiring ............................................... 49 Excluding a bean from autowiring .............................................................. 50 Method injection ............................................................................................... 50 Lookup method injection ........................................................................... 51 Arbitrary method replacement ................................................................... 53 4.5. Bean scopes ..................................................................................................... 54 The singleton scope ......................................................................................... 55 The prototype scope ......................................................................................... 55 Singleton beans with prototype-bean dependencies ............................................ 56 Request, session, and global session scopes .................................................... 56 Initial web configuration ............................................................................ 57 Request scope ......................................................................................... 58 Session scope .......................................................................................... 58 Global session scope ............................................................................... 58 Scoped beans as dependencies ................................................................ 58 Custom scopes ................................................................................................ 60 Creating a custom scope .......................................................................... 60 Using a custom scope .............................................................................. 61 4.6. Customizing the nature of a bean ....................................................................... 62 Lifecycle callbacks ............................................................................................ 62 Initialization callbacks ............................................................................... 63 Destruction callbacks ................................................................................ 64 Default initialization and destroy methods .................................................. 64 Combining lifecycle mechanisms ............................................................... 66 Startup and shutdown callbacks ................................................................ 66 Shutting down the Spring IoC container gracefully in non-web applications ................................................................................................................. 68 ApplicationContextAware and BeanNameAware ................................................. 68 Other Aware interfaces ..................................................................................... 69 4.7. Bean definition inheritance ................................................................................. 71 4.8. Container Extension Points ................................................................................ 72 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iv Customizing beans using a BeanPostProcessor ................................................. 72 Example: Hello World, BeanPostProcessor-style ........................................ 74 Example: The RequiredAnnotationBeanPostProcessor ............................... 75 Customizing configuration metadata with a BeanFactoryPostProcessor ................ 75 Example: the Class name substitution PropertyPlaceholderConfigurer .......... 76 Example: the PropertyOverrideConfigurer .................................................. 77 Customizing instantiation logic with a FactoryBean ............................................. 78 4.9. Annotation-based container configuration ............................................................ 79 @Required ....................................................................................................... 80 @Autowired ..................................................................................................... 80 Fine-tuning annotation-based autowiring with qualifiers ....................................... 83 Using generics as autowiring qualifiers .............................................................. 89 CustomAutowireConfigurer ................................................................................ 90 @Resource ...................................................................................................... 90 @PostConstruct and @PreDestroy .................................................................... 92 4.10. Classpath scanning and managed components ................................................. 92 @Component and further stereotype annotations ............................................... 93 Meta-annotations .............................................................................................. 93 Automatically detecting classes and registering bean definitions .......................... 94 Using filters to customize scanning ................................................................... 95 Defining bean metadata within components ....................................................... 96 Naming autodetected components ..................................................................... 97 Providing a scope for autodetected components ................................................ 98 Providing qualifier metadata with annotations ..................................................... 99 4.11. Using JSR 330 Standard Annotations ............................................................... 99 Dependency Injection with @Inject and @Named ............................................. 100 @Named: a standard equivalent to the @Component annotation ....................... 100 Limitations of the standard approach ............................................................... 101 4.12. Java-based container configuration ................................................................. 102 Basic concepts: @Bean and @Configuration ................................................... 102 Instantiating the Spring container using AnnotationConfigApplicationContext ....... 103 Simple construction ................................................................................ 103 Building the container programmatically using register(Class…) ........... 104 Enabling component scanning with scan(String…) .................................... 104 Support for web applications with AnnotationConfigWebApplicationContext ............................................................................................................... 105 Using the @Bean annotation .......................................................................... 106 Declaring a bean .................................................................................... 107 Receiving lifecycle callbacks ................................................................... 107 Specifying bean scope ............................................................................ 108 Customizing bean naming ....................................................................... 109 Bean aliasing ......................................................................................... 109 Bean description ..................................................................................... 110 Using the @Configuration annotation ............................................................... 110 Injecting inter-bean dependencies ............................................................ 110 Lookup method injection ......................................................................... 111 Further information about how Java-based configuration works internally .... 111 Composing Java-based configurations ............................................................. 112 Using the @Import annotation ................................................................. 112 Conditionally including @Configuration classes or @Beans ....................... 116 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation v Combining Java and XML configuration ................................................... 117 4.13. Bean definition profiles and environment abstraction ........................................ 120 4.14. PropertySource Abstraction ............................................................................ 120 4.15. Registering a LoadTimeWeaver ...................................................................... 120 4.16. Additional Capabilities of the ApplicationContext .............................................. 120 Internationalization using MessageSource ........................................................ 121 Standard and Custom Events .......................................................................... 124 Convenient access to low-level resources ........................................................ 127 Convenient ApplicationContext instantiation for web applications ....................... 128 Deploying a Spring ApplicationContext as a J2EE RAR file ............................... 128 4.17. The BeanFactory ........................................................................................... 129 BeanFactory or ApplicationContext? ................................................................ 129 Glue code and the evil singleton ..................................................................... 131 5. Resources .................................................................................................................. 132 5.1. Introduction ..................................................................................................... 132 5.2. The Resource interface .................................................................................... 132 5.3. Built-in Resource implementations .................................................................... 133 UrlResource ................................................................................................... 133 ClassPathResource ........................................................................................ 133 FileSystemResource ....................................................................................... 134 ServletContextResource .................................................................................. 134 InputStreamResource ..................................................................................... 134 ByteArrayResource ......................................................................................... 134 5.4. The ResourceLoader ....................................................................................... 134 5.5. The ResourceLoaderAware interface ................................................................ 135 5.6. Resources as dependencies ............................................................................. 136 5.7. Application contexts and Resource paths .......................................................... 137 Constructing application contexts ..................................................................... 137 Constructing ClassPathXmlApplicationContext instances - shortcuts .......... 137 Wildcards in application context constructor resource paths ............................... 138 Ant-style Patterns ................................................................................... 138 The Classpath*: portability classpath*: prefix ............................................ 139 Other notes relating to wildcards ............................................................. 139 FileSystemResource caveats .......................................................................... 140 6. Validation, Data Binding, and Type Conversion ............................................................ 141 6.1. Introduction ..................................................................................................... 141 6.2. Validation using Spring’s Validator interface ...................................................... 141 6.3. Resolving codes to error messages .................................................................. 143 6.4. Bean manipulation and the BeanWrapper ......................................................... 144 Setting and getting basic and nested properties ............................................... 144 Built-in PropertyEditor implementations ............................................................ 146 Registering additional custom PropertyEditors .......................................... 149 6.5. Spring Type Conversion ................................................................................... 151 Converter SPI ................................................................................................ 151 ConverterFactory ............................................................................................ 152 GenericConverter ........................................................................................... 153 ConditionalGenericConverter ................................................................... 154 ConversionService API ................................................................................... 154 Configuring a ConversionService ..................................................................... 154 Using a ConversionService programmatically ................................................... 155 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation vi 6.6. Spring Field Formatting .................................................................................... 155 Formatter SPI ................................................................................................. 156 Annotation-driven Formatting ........................................................................... 157 Format Annotation API ............................................................................ 158 FormatterRegistry SPI ..................................................................................... 159 FormatterRegistrar SPI ................................................................................... 159 Configuring Formatting in Spring MVC ............................................................. 159 6.7. Configuring a global date & time format ............................................................ 161 6.8. Spring Validation ............................................................................................. 163 Overview of the JSR-303 Bean Validation API ................................................. 163 Configuring a Bean Validation Provider ............................................................ 164 Injecting a Validator ................................................................................ 164 Configuring Custom Constraints .............................................................. 164 Additional Configuration Options .............................................................. 165 Configuring a DataBinder ................................................................................ 165 Spring MVC 3 Validation ................................................................................. 166 Triggering @Controller Input Validation .................................................... 166 Configuring a Validator for use by Spring MVC ......................................... 166 Configuring a JSR-303/JSR-349 Validator for use by Spring MVC .............. 167 7. Spring Expression Language (SpEL) ........................................................................... 168 7.1. Introduction ..................................................................................................... 168 7.2. Feature Overview ............................................................................................ 168 7.3. Expression Evaluation using Spring’s Expression Interface ................................. 169 The EvaluationContext interface ...................................................................... 171 Type Conversion .................................................................................... 171 7.4. Expression support for defining bean definitions ................................................ 172 XML based configuration ................................................................................ 172 Annotation-based configuration ........................................................................ 173 7.5. Language Reference ........................................................................................ 174 Literal expressions .......................................................................................... 174 Properties, Arrays, Lists, Maps, Indexers ......................................................... 174 Inline lists ....................................................................................................... 175 Array construction ........................................................................................... 175 Methods ......................................................................................................... 176 Operators ....................................................................................................... 176 Relational operators ................................................................................ 176 Logical operators .................................................................................... 177 Mathematical operators ........................................................................... 177 Assignment .................................................................................................... 178 Types ............................................................................................................. 178 Constructors ................................................................................................... 179 Variables ........................................................................................................ 179 The #this and #root variables .................................................................. 179 Functions ....................................................................................................... 180 Bean references ............................................................................................. 180 Ternary Operator (If-Then-Else) ....................................................................... 180 The Elvis Operator ......................................................................................... 181 Safe Navigation operator ................................................................................ 181 Collection Selection ........................................................................................ 182 Collection Projection ....................................................................................... 182 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation vii Expression templating ..................................................................................... 183 7.6. Classes used in the examples .......................................................................... 183 8. Aspect Oriented Programming with Spring ................................................................... 187 8.1. Introduction ..................................................................................................... 187 AOP concepts ................................................................................................ 187 Spring AOP capabilities and goals ................................................................... 189 AOP Proxies .................................................................................................. 190 8.2. @AspectJ support ........................................................................................... 190 Enabling @AspectJ Support ............................................................................ 190 Enabling @AspectJ Support with Java configuration ................................. 190 Enabling @AspectJ Support with XML configuration ................................. 191 Declaring an aspect ........................................................................................ 191 Declaring a pointcut ........................................................................................ 192 Supported Pointcut Designators .............................................................. 192 Combining pointcut expressions .............................................................. 194 Sharing common pointcut definitions ........................................................ 194 Examples ............................................................................................... 196 Writing good pointcuts ............................................................................ 198 Declaring advice ............................................................................................. 199 Before advice ......................................................................................... 199 After returning advice .............................................................................. 200 After throwing advice .............................................................................. 200 After (finally) advice ................................................................................ 201 Around advice ........................................................................................ 202 Advice parameters .................................................................................. 203 Advice ordering ...................................................................................... 206 Introductions ................................................................................................... 206 Aspect instantiation models ............................................................................. 207 Example ......................................................................................................... 208 8.3. Schema-based AOP support ............................................................................ 209 Declaring an aspect ........................................................................................ 210 Declaring a pointcut ........................................................................................ 210 Declaring advice ............................................................................................. 212 Before advice ......................................................................................... 212 After returning advice .............................................................................. 212 After throwing advice .............................................................................. 213 After (finally) advice ................................................................................ 214 Around advice ........................................................................................ 214 Advice parameters .................................................................................. 215 Advice ordering ...................................................................................... 216 Introductions ................................................................................................... 217 Aspect instantiation models ............................................................................. 217 Advisors ......................................................................................................... 217 Example ......................................................................................................... 218 8.4. Choosing which AOP declaration style to use .................................................... 220 Spring AOP or full AspectJ? ........................................................................... 220 @AspectJ or XML for Spring AOP? ................................................................. 221 8.5. Mixing aspect types ......................................................................................... 222 8.6. Proxying mechanisms ...................................................................................... 222 Understanding AOP proxies ............................................................................ 223 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation viii 8.7. Programmatic creation of @AspectJ Proxies ..................................................... 225 8.8. Using AspectJ with Spring applications ............................................................. 225 Using AspectJ to dependency inject domain objects with Spring ........................ 226 Unit testing @Configurable objects .......................................................... 228 Working with multiple application contexts ................................................ 228 Other Spring aspects for AspectJ .................................................................... 229 Configuring AspectJ aspects using Spring IoC ................................................. 229 Load-time weaving with AspectJ in the Spring Framework ................................. 230 A first example ....................................................................................... 231 Aspects .................................................................................................. 234 ' META-INF/aop.xml' ............................................................................... 234 Required libraries (JARS) ........................................................................ 234 Spring configuration ................................................................................ 235 Environment-specific configuration ........................................................... 237 8.9. Further Resources ........................................................................................... 239 9. Spring AOP APIs ....................................................................................................... 240 9.1. Introduction ..................................................................................................... 240 9.2. Pointcut API in Spring ...................................................................................... 240 Concepts ........................................................................................................ 240 Operations on pointcuts .................................................................................. 241 AspectJ expression pointcuts .......................................................................... 241 Convenience pointcut implementations ............................................................ 241 Static pointcuts ....................................................................................... 241 Dynamic pointcuts .................................................................................. 242 Pointcut superclasses ..................................................................................... 243 Custom pointcuts ............................................................................................ 243 9.3. Advice API in Spring ........................................................................................ 243 Advice lifecycles ............................................................................................. 243 Advice types in Spring .................................................................................... 244 Interception around advice ...................................................................... 244 Before advice ......................................................................................... 244 Throws advice ........................................................................................ 245 After Returning advice ............................................................................ 246 Introduction advice .................................................................................. 247 9.4. Advisor API in Spring ....................................................................................... 249 9.5. Using the ProxyFactoryBean to create AOP proxies ........................................... 250 Basics ............................................................................................................ 250 JavaBean properties ....................................................................................... 250 JDK- and CGLIB-based proxies ...................................................................... 251 Proxying interfaces ......................................................................................... 252 Proxying classes ............................................................................................ 254 Using global advisors ...................................................................................... 255 9.6. Concise proxy definitions ................................................................................. 255 9.7. Creating AOP proxies programmatically with the ProxyFactory ............................ 256 9.8. Manipulating advised objects ............................................................................ 257 9.9. Using the "auto-proxy" facility ........................................................................... 258 Autoproxy bean definitions .............................................................................. 258 BeanNameAutoProxyCreator ................................................................... 259 DefaultAdvisorAutoProxyCreator .............................................................. 259 AbstractAdvisorAutoProxyCreator ............................................................ 260 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation ix Using metadata-driven auto-proxying ............................................................... 260 9.10. Using TargetSources ...................................................................................... 262 Hot swappable target sources ......................................................................... 263 Pooling target sources .................................................................................... 263 Prototype target sources ................................................................................. 265 ThreadLocal target sources ............................................................................. 265 9.11. Defining new Advice types ............................................................................. 265 9.12. Further resources ........................................................................................... 266 10. Testing ..................................................................................................................... 267 10.1. Introduction to Spring Testing ......................................................................... 267 10.2. Unit Testing ................................................................................................... 267 Mock Objects ................................................................................................. 267 Environment ........................................................................................... 267 JNDI ...................................................................................................... 267 Servlet API ............................................................................................. 267 Portlet API ............................................................................................. 268 Unit Testing support Classes .......................................................................... 268 General utilities ...................................................................................... 268 Spring MVC ........................................................................................... 268 10.3. Integration Testing ......................................................................................... 268 Overview ........................................................................................................ 268 Goals of Integration Testing ............................................................................ 269 Context management and caching ........................................................... 269 Dependency Injection of test fixtures ....................................................... 269 Transaction management ........................................................................ 270 Support classes for integration testing ..................................................... 270 JDBC Testing Support .................................................................................... 271 Annotations .................................................................................................... 271 Spring Testing Annotations ..................................................................... 271 Standard Annotation Support .................................................................. 276 Spring JUnit Testing Annotations ............................................................. 277 Meta-Annotation Support for Testing ........................................................ 278 Spring TestContext Framework ....................................................................... 279 Key abstractions ..................................................................................... 280 Context management .............................................................................. 281 Dependency injection of test fixtures ........................................................ 297 Testing request and session scoped beans .............................................. 299 Transaction management ........................................................................ 301 TestContext Framework support classes .................................................. 304 Spring MVC Test Framework .......................................................................... 306 Server-Side Tests ................................................................................... 306 Client-Side REST Tests .......................................................................... 312 PetClinic Example .......................................................................................... 313 10.4. Further Resources ......................................................................................... 314 IV. Data Access ..................................................................................................................... 316 11. Transaction Management .......................................................................................... 317 11.1. Introduction to Spring Framework transaction management .............................. 317 11.2. Advantages of the Spring Framework’s transaction support model ..................... 317 Global transactions ......................................................................................... 317 Local transactions ........................................................................................... 318 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation x Spring Framework’s consistent programming model ......................................... 318 11.3. Understanding the Spring Framework transaction abstraction ............................ 319 11.4. Synchronizing resources with transactions ....................................................... 323 High-level synchronization approach ................................................................ 323 Low-level synchronization approach ................................................................. 323 TransactionAwareDataSourceProxy ................................................................. 324 11.5. Declarative transaction management ............................................................... 324 Understanding the Spring Framework’s declarative transaction implementation ... 325 Example of declarative transaction implementation ........................................... 326 Rolling back a declarative transaction .............................................................. 330 Configuring different transactional semantics for different beans ........................ 331 settings ....................................................................................... 333 Using @Transactional ..................................................................................... 335 @Transactional settings .......................................................................... 339 Multiple Transaction Managers with @Transactional ................................. 340 Custom shortcut annotations ................................................................... 341 Transaction propagation .................................................................................. 341 Required ................................................................................................ 342 RequiresNew .......................................................................................... 342 Nested ................................................................................................... 343 Advising transactional operations ..................................................................... 343 Using @Transactional with AspectJ ................................................................. 346 11.6. Programmatic transaction management ........................................................... 347 Using the TransactionTemplate ....................................................................... 347 Specifying transaction settings ................................................................ 349 Using the PlatformTransactionManager ............................................................ 349 11.7. Choosing between programmatic and declarative transaction management ........ 350 11.8. Application server-specific integration .............................................................. 350 IBM WebSphere ............................................................................................. 351 Oracle WebLogic Server ................................................................................. 351 11.9. Solutions to common problems ....................................................................... 351 Use of the wrong transaction manager for a specific DataSource ....................... 351 11.10. Further Resources ....................................................................................... 351 12. DAO support ............................................................................................................ 352 12.1. Introduction .................................................................................................... 352 12.2. Consistent exception hierarchy ....................................................................... 352 12.3. Annotations used for configuring DAO or Repository classes ............................ 353 13. Data access with JDBC ............................................................................................ 355 13.1. Introduction to Spring Framework JDBC .......................................................... 355 Choosing an approach for JDBC database access ........................................... 355 Package hierarchy .......................................................................................... 356 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ................................................................................................................. 357 JdbcTemplate ................................................................................................. 357 Examples of JdbcTemplate class usage ................................................... 357 JdbcTemplate best practices ................................................................... 359 NamedParameterJdbcTemplate ....................................................................... 361 SQLExceptionTranslator .................................................................................. 363 Executing statements ...................................................................................... 365 Running queries ............................................................................................. 365 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xi Updating the database .................................................................................... 366 Retrieving auto-generated keys ....................................................................... 367 13.3. Controlling database connections .................................................................... 367 DataSource .................................................................................................... 367 DataSourceUtils .............................................................................................. 369 SmartDataSource ........................................................................................... 369 AbstractDataSource ........................................................................................ 369 SingleConnectionDataSource .......................................................................... 369 DriverManagerDataSource .............................................................................. 369 TransactionAwareDataSourceProxy ................................................................. 370 DataSourceTransactionManager ...................................................................... 370 NativeJdbcExtractor ........................................................................................ 370 13.4. JDBC batch operations .................................................................................. 371 Basic batch operations with the JdbcTemplate ................................................. 371 Batch operations with a List of objects ............................................................. 372 Batch operations with multiple batches ............................................................ 373 13.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 374 Inserting data using SimpleJdbcInsert .............................................................. 374 Retrieving auto-generated keys using SimpleJdbcInsert .................................... 375 Specifying columns for a SimpleJdbcInsert ...................................................... 376 Using SqlParameterSource to provide parameter values ................................... 376 Calling a stored procedure with SimpleJdbcCall ............................................... 377 Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 379 How to define SqlParameters .......................................................................... 380 Calling a stored function using SimpleJdbcCall ................................................. 381 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 381 13.6. Modeling JDBC operations as Java objects ..................................................... 382 SqlQuery ........................................................................................................ 383 MappingSqlQuery ........................................................................................... 383 SqlUpdate ...................................................................................................... 384 StoredProcedure ............................................................................................. 385 13.7. Common problems with parameter and data value handling .............................. 388 Providing SQL type information for parameters ................................................. 389 Handling BLOB and CLOB objects .................................................................. 389 Passing in lists of values for IN clause ............................................................ 390 Handling complex types for stored procedure calls ........................................... 391 13.8. Embedded database support .......................................................................... 392 Why use an embedded database? .................................................................. 392 Creating an embedded database instance using Spring XML ............................ 392 Creating an embedded database instance programmatically .............................. 392 Extending the embedded database support ...................................................... 393 Using HSQL ................................................................................................... 393 Using H2 ........................................................................................................ 393 Using Derby ................................................................................................... 393 Testing data access logic with an embedded database ..................................... 393 13.9. Initializing a DataSource ................................................................................. 394 Initializing a database instance using Spring XML ............................................. 394 Initialization of Other Components that Depend on the Database ............... 395 14. Object Relational Mapping (ORM) Data Access .......................................................... 397 14.1. Introduction to ORM with Spring ..................................................................... 397 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xii 14.2. General ORM integration considerations ......................................................... 398 Resource and transaction management ........................................................... 398 Exception translation ....................................................................................... 399 14.3. Hibernate ....................................................................................................... 399 SessionFactory setup in a Spring container ...................................................... 400 Implementing DAOs based on plain Hibernate 3 API ........................................ 400 Declarative transaction demarcation ................................................................ 402 Programmatic transaction demarcation ............................................................ 404 Transaction management strategies ................................................................ 405 Comparing container-managed and locally defined resources ............................ 407 Spurious application server warnings with Hibernate ......................................... 408 14.4. JDO .............................................................................................................. 409 PersistenceManagerFactory setup ................................................................... 409 Implementing DAOs based on the plain JDO API ............................................. 410 Transaction management ................................................................................ 412 JdoDialect ...................................................................................................... 413 14.5. JPA ............................................................................................................... 414 Three options for JPA setup in a Spring environment ........................................ 414 LocalEntityManagerFactoryBean .............................................................. 414 Obtaining an EntityManagerFactory from JNDI ......................................... 415 LocalContainerEntityManagerFactoryBean ............................................... 415 Dealing with multiple persistence units ..................................................... 417 Implementing DAOs based on plain JPA .......................................................... 418 Transaction Management ................................................................................ 420 JpaDialect ...................................................................................................... 421 15. Marshalling XML using O/X Mappers ......................................................................... 423 15.1. Introduction .................................................................................................... 423 Ease of configuration ...................................................................................... 423 Consistent Interfaces ...................................................................................... 423 Consistent Exception Hierarchy ....................................................................... 423 15.2. Marshaller and Unmarshaller .......................................................................... 423 Marshaller ...................................................................................................... 423 Unmarshaller .................................................................................................. 424 XmlMappingException ..................................................................................... 425 15.3. Using Marshaller and Unmarshaller ................................................................. 425 15.4. XML Schema-based Configuration .................................................................. 427 15.5. JAXB ............................................................................................................. 427 Jaxb2Marshaller ............................................................................................. 428 XML Schema-based Configuration ........................................................... 428 15.6. Castor ........................................................................................................... 429 CastorMarshaller ............................................................................................ 429 Mapping ......................................................................................................... 429 XML Schema-based Configuration ........................................................... 429 15.7. XMLBeans ..................................................................................................... 430 XmlBeansMarshaller ....................................................................................... 430 XML Schema-based Configuration ........................................................... 430 15.8. JiBX .............................................................................................................. 431 JibxMarshaller ................................................................................................ 431 XML Schema-based Configuration ........................................................... 431 15.9. XStream ........................................................................................................ 432 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xiii XStreamMarshaller ......................................................................................... 432 V. The Web ........................................................................................................................... 434 16. Web MVC framework ................................................................................................ 435 16.1. Introduction to Spring Web MVC framework .................................................... 435 Features of Spring Web MVC ......................................................................... 436 Pluggability of other MVC implementations ...................................................... 437 16.2. The DispatcherServlet .................................................................................... 437 Special Bean Types In the WebApplicationContext ........................................... 440 Default DispatcherServlet Configuration ........................................................... 441 DispatcherServlet Processing Sequence .......................................................... 441 16.3. Implementing Controllers ................................................................................ 443 Defining a controller with @Controller .............................................................. 443 Mapping Requests With Using @RequestMapping ........................................... 444 New Support Classes for @RequestMapping methods in Spring MVC 3.1 .. 446 URI Template Patterns ........................................................................... 447 URI Template Patterns with Regular Expressions ..................................... 448 Path Patterns ......................................................................................... 449 Patterns with Placeholders ...................................................................... 449 Matrix Variables ...................................................................................... 449 Consumable Media Types ....................................................................... 450 Producible Media Types .......................................................................... 451 Request Parameters and Header Values ................................................. 451 Defining @RequestMapping handler methods .................................................. 452 Supported method argument types .......................................................... 452 Supported method return types ............................................................... 454 Binding request parameters to method parameters with @RequestParam ... 455 Mapping the request body with the @RequestBody annotation .................. 456 Mapping the response body with the @ResponseBody annotation ............. 457 Creating REST Controllers with the @RestController annotation ................ 457 Using HttpEntity ...................................................................................... 457 Using @ModelAttribute on a method ....................................................... 458 Using @ModelAttribute on a method argument ......................................... 459 Using @SessionAttributes to store model attributes in the HTTP session between requests ................................................................................... 461 Specifying redirect and flash attributes ..................................................... 461 Working with "application/x-www-form-urlencoded" data ............................ 462 Mapping cookie values with the @CookieValue annotation ........................ 462 Mapping request header attributes with the @RequestHeader annotation ... 463 Method Parameters And Type Conversion ............................................... 463 Customizing WebDataBinder initialization ................................................. 464 Support for the Last-Modified Response Header To Facilitate Content Caching ................................................................................................. 465 Assisting Controllers with the @ControllerAdvice annotation ...................... 465 Asynchronous Request Processing .................................................................. 466 Exception Handling for Async Requests ................................................... 467 Intercepting Async Requests ................................................................... 467 Configuration for Async Request Processing ............................................ 468 Testing Controllers ......................................................................................... 469 16.4. Handler mappings .......................................................................................... 469 Intercepting requests with a HandlerInterceptor ................................................ 469 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xiv 16.5. Resolving views ............................................................................................. 471 Resolving views with the ViewResolver interface .............................................. 471 Chaining ViewResolvers ................................................................................. 473 Redirecting to views ....................................................................................... 474 RedirectView .......................................................................................... 474 The redirect: prefix ................................................................................. 475 The forward: prefix ................................................................................. 475 ContentNegotiatingViewResolver ..................................................................... 475 16.6. Using flash attributes ..................................................................................... 478 16.7. Building URIs ................................................................................................. 479 16.8. Building URIs to Controllers and methods ....................................................... 480 16.9. Using locales ................................................................................................. 480 Obtaining Time Zone Information .................................................................... 481 AcceptHeaderLocaleResolver .......................................................................... 481 CookieLocaleResolver ..................................................................................... 481 SessionLocaleResolver ................................................................................... 481 LocaleChangeInterceptor ................................................................................ 482 16.10. Using themes ............................................................................................... 482 Overview of themes ........................................................................................ 482 Defining themes ............................................................................................. 482 Theme resolvers ............................................................................................. 483 16.11. Spring’s multipart (file upload) support ........................................................... 483 Introduction .................................................................................................... 483 Using a MultipartResolver with Commons FileUpload ........................................ 484 Using a MultipartResolver with Servlet 3.0 ....................................................... 484 Handling a file upload in a form ...................................................................... 484 Handling a file upload request from programmatic clients .................................. 486 16.12. Handling exceptions ..................................................................................... 486 HandlerExceptionResolver ............
Not Using Commons Logging ................................................................... 12 Using SLF4J ............................................................................................ 13 Using Log4J ............................................................................................. 14 II. What’s New in Spring Framework 4.x .................................................................................... 16 3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .................................................................. 17 3.2. Removed Deprecated Packages and Methods .................................................... 17 3.3. Java 8 (as well as 6 and 7) ............................................................................... 17 3.4. Java EE 6 and 7 ............................................................................................... 18 3.5. Groovy Bean Definition DSL .............................................................................. 18 3.6. Core Container Improvements ............................................................................ 19 3.7. General Web Improvements ............................................................................... 19 3.8. WebSocket, SockJS, and STOMP Messaging ..................................................... 19 3.9. Testing Improvements ........................................................................................ 20 III. Core Technologies .............................................................................................................. 21 4. The IoC container ........................................................................................................ 22 4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview ............................................................................................ 22 Configuration metadata ..................................................................................... 23 Instantiating a container .................................................................................... 24 Composing XML-based configuration metadata .......................................... 25 Using the container .......................................................................................... 26 4.3. Bean overview ................................................................................................... 27 Naming beans .................................................................................................. 28 Aliasing a bean outside the bean definition ................................................ 28 Instantiating beans ........................................................................................... 29 Instantiation with a constructor .................................................................. 29 Instantiation with a static factory method .................................................... 30 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iii Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ................................................................................................... 32 Dependency injection ....................................................................................... 32 Constructor-based dependency injection .................................................... 32 Setter-based dependency injection ............................................................ 34 Dependency resolution process ................................................................. 35 Examples of dependency injection ............................................................. 36 Dependencies and configuration in detail ........................................................... 38 Straight values (primitives, Strings, and so on) ........................................... 38 References to other beans (collaborators) .................................................. 40 Inner beans .............................................................................................. 41 Collections ............................................................................................... 41 Null and empty string values ..................................................................... 44 XML shortcut with the p-namespace .......................................................... 44 XML shortcut with the c-namespace .......................................................... 46 Compound property names ....................................................................... 46 Using depends-on ............................................................................................ 47 Lazy-initialized beans ....................................................................................... 47 Autowiring collaborators .................................................................................... 48 Limitations and disadvantages of autowiring ............................................... 49 Excluding a bean from autowiring .............................................................. 50 Method injection ............................................................................................... 50 Lookup method injection ........................................................................... 51 Arbitrary method replacement ................................................................... 53 4.5. Bean scopes ..................................................................................................... 54 The singleton scope ......................................................................................... 55 The prototype scope ......................................................................................... 55 Singleton beans with prototype-bean dependencies ............................................ 56 Request, session, and global session scopes .................................................... 56 Initial web configuration ............................................................................ 57 Request scope ......................................................................................... 58 Session scope .......................................................................................... 58 Global session scope ............................................................................... 58 Scoped beans as dependencies ................................................................ 58 Custom scopes ................................................................................................ 60 Creating a custom scope .......................................................................... 60 Using a custom scope .............................................................................. 61 4.6. Customizing the nature of a bean ....................................................................... 62 Lifecycle callbacks ............................................................................................ 62 Initialization callbacks ............................................................................... 63 Destruction callbacks ................................................................................ 64 Default initialization and destroy methods .................................................. 64 Combining lifecycle mechanisms ............................................................... 66 Startup and shutdown callbacks ................................................................ 66 Shutting down the Spring IoC container gracefully in non-web applications ................................................................................................................. 68 ApplicationContextAware and BeanNameAware ................................................. 68 Other Aware interfaces ..................................................................................... 69 4.7. Bean definition inheritance ................................................................................. 71 4.8. Container Extension Points ................................................................................ 72 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iv Customizing beans using a BeanPostProcessor ................................................. 72 Example: Hello World, BeanPostProcessor-style ........................................ 74 Example: The RequiredAnnotationBeanPostProcessor ............................... 75 Customizing configuration metadata with a BeanFactoryPostProcessor ................ 75 Example: the Class name substitution PropertyPlaceholderConfigurer .......... 76 Example: the PropertyOverrideConfigurer .................................................. 77 Customizing instantiation logic with a FactoryBean ............................................. 78 4.9. Annotation-based container configuration ............................................................ 79 @Required ....................................................................................................... 80 @Autowired ..................................................................................................... 80 Fine-tuning annotation-based autowiring with qualifiers ....................................... 83 Using generics as autowiring qualifiers .............................................................. 89 CustomAutowireConfigurer ................................................................................ 90 @Resource ...................................................................................................... 90 @PostConstruct and @PreDestroy .................................................................... 92 4.10. Classpath scanning and managed components ................................................. 92 @Component and further stereotype annotations ............................................... 93 Meta-annotations .............................................................................................. 93 Automatically detecting classes and registering bean definitions .......................... 94 Using filters to customize scanning ................................................................... 95 Defining bean metadata within components ....................................................... 96 Naming autodetected components ..................................................................... 97 Providing a scope for autodetected components ................................................ 98 Providing qualifier metadata with annotations ..................................................... 99 4.11. Using JSR 330 Standard Annotations ............................................................... 99 Dependency Injection with @Inject and @Named ............................................. 100 @Named: a standard equivalent to the @Component annotation ....................... 100 Limitations of the standard approach ............................................................... 101 4.12. Java-based container configuration ................................................................. 102 Basic concepts: @Bean and @Configuration ................................................... 102 Instantiating the Spring container using AnnotationConfigApplicationContext ....... 103 Simple construction ................................................................................ 103 Building the container programmatically using register(Class…) ........... 104 Enabling component scanning with scan(String…) .................................... 104 Support for web applications with AnnotationConfigWebApplicationContext ............................................................................................................... 105 Using the @Bean annotation .......................................................................... 106 Declaring a bean .................................................................................... 107 Receiving lifecycle callbacks ................................................................... 107 Specifying bean scope ............................................................................ 108 Customizing bean naming ....................................................................... 109 Bean aliasing ......................................................................................... 109 Bean description ..................................................................................... 110 Using the @Configuration annotation ............................................................... 110 Injecting inter-bean dependencies ............................................................ 110 Lookup method injection ......................................................................... 111 Further information about how Java-based configuration works internally .... 111 Composing Java-based configurations ............................................................. 112 Using the @Import annotation ................................................................. 112 Conditionally including @Configuration classes or @Beans ....................... 116 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation v Combining Java and XML configuration ................................................... 117 4.13. Bean definition profiles and environment abstraction ........................................ 120 4.14. PropertySource Abstraction ............................................................................ 120 4.15. Registering a LoadTimeWeaver ...................................................................... 120 4.16. Additional Capabilities of the ApplicationContext .............................................. 120 Internationalization using MessageSource ........................................................ 121 Standard and Custom Events .......................................................................... 124 Convenient access to low-level resources ........................................................ 127 Convenient ApplicationContext instantiation for web applications ....................... 128 Deploying a Spring ApplicationContext as a J2EE RAR file ............................... 128 4.17. The BeanFactory ........................................................................................... 129 BeanFactory or ApplicationContext? ................................................................ 129 Glue code and the evil singleton ..................................................................... 131 5. Resources .................................................................................................................. 132 5.1. Introduction ..................................................................................................... 132 5.2. The Resource interface .................................................................................... 132 5.3. Built-in Resource implementations .................................................................... 133 UrlResource ................................................................................................... 133 ClassPathResource ........................................................................................ 133 FileSystemResource ....................................................................................... 134 ServletContextResource .................................................................................. 134 InputStreamResource ..................................................................................... 134 ByteArrayResource ......................................................................................... 134 5.4. The ResourceLoader ....................................................................................... 134 5.5. The ResourceLoaderAware interface ................................................................ 135 5.6. Resources as dependencies ............................................................................. 136 5.7. Application contexts and Resource paths .......................................................... 137 Constructing application contexts ..................................................................... 137 Constructing ClassPathXmlApplicationContext instances - shortcuts .......... 137 Wildcards in application context constructor resource paths ............................... 138 Ant-style Patterns ................................................................................... 138 The Classpath*: portability classpath*: prefix ............................................ 139 Other notes relating to wildcards ............................................................. 139 FileSystemResource caveats .......................................................................... 140 6. Validation, Data Binding, and Type Conversion ............................................................ 141 6.1. Introduction ..................................................................................................... 141 6.2. Validation using Spring’s Validator interface ...................................................... 141 6.3. Resolving codes to error messages .................................................................. 143 6.4. Bean manipulation and the BeanWrapper ......................................................... 144 Setting and getting basic and nested properties ............................................... 144 Built-in PropertyEditor implementations ............................................................ 146 Registering additional custom PropertyEditors .......................................... 149 6.5. Spring Type Conversion ................................................................................... 151 Converter SPI ................................................................................................ 151 ConverterFactory ............................................................................................ 152 GenericConverter ........................................................................................... 153 ConditionalGenericConverter ................................................................... 154 ConversionService API ................................................................................... 154 Configuring a ConversionService ..................................................................... 154 Using a ConversionService programmatically ................................................... 155 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation vi 6.6. Spring Field Formatting .................................................................................... 155 Formatter SPI ................................................................................................. 156 Annotation-driven Formatting ........................................................................... 157 Format Annotation API ............................................................................ 158 FormatterRegistry SPI ..................................................................................... 159 FormatterRegistrar SPI ................................................................................... 159 Configuring Formatting in Spring MVC ............................................................. 159 6.7. Configuring a global date & time format ............................................................ 161 6.8. Spring Validation ............................................................................................. 163 Overview of the JSR-303 Bean Validation API ................................................. 163 Configuring a Bean Validation Provider ............................................................ 164 Injecting a Validator ................................................................................ 164 Configuring Custom Constraints .............................................................. 164 Additional Configuration Options .............................................................. 165 Configuring a DataBinder ................................................................................ 165 Spring MVC 3 Validation ................................................................................. 166 Triggering @Controller Input Validation .................................................... 166 Configuring a Validator for use by Spring MVC ......................................... 166 Configuring a JSR-303/JSR-349 Validator for use by Spring MVC .............. 167 7. Spring Expression Language (SpEL) ........................................................................... 168 7.1. Introduction ..................................................................................................... 168 7.2. Feature Overview ............................................................................................ 168 7.3. Expression Evaluation using Spring’s Expression Interface ................................. 169 The EvaluationContext interface ...................................................................... 171 Type Conversion .................................................................................... 171 7.4. Expression support for defining bean definitions ................................................ 172 XML based configuration ................................................................................ 172 Annotation-based configuration ........................................................................ 173 7.5. Language Reference ........................................................................................ 174 Literal expressions .......................................................................................... 174 Properties, Arrays, Lists, Maps, Indexers ......................................................... 174 Inline lists ....................................................................................................... 175 Array construction ........................................................................................... 175 Methods ......................................................................................................... 176 Operators ....................................................................................................... 176 Relational operators ................................................................................ 176 Logical operators .................................................................................... 177 Mathematical operators ........................................................................... 177 Assignment .................................................................................................... 178 Types ............................................................................................................. 178 Constructors ................................................................................................... 179 Variables ........................................................................................................ 179 The #this and #root variables .................................................................. 179 Functions ....................................................................................................... 180 Bean references ............................................................................................. 180 Ternary Operator (If-Then-Else) ....................................................................... 180 The Elvis Operator ......................................................................................... 181 Safe Navigation operator ................................................................................ 181 Collection Selection ........................................................................................ 182 Collection Projection ....................................................................................... 182 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation vii Expression templating ..................................................................................... 183 7.6. Classes used in the examples .......................................................................... 183 8. Aspect Oriented Programming with Spring ................................................................... 187 8.1. Introduction ..................................................................................................... 187 AOP concepts ................................................................................................ 187 Spring AOP capabilities and goals ................................................................... 189 AOP Proxies .................................................................................................. 190 8.2. @AspectJ support ........................................................................................... 190 Enabling @AspectJ Support ............................................................................ 190 Enabling @AspectJ Support with Java configuration ................................. 190 Enabling @AspectJ Support with XML configuration ................................. 191 Declaring an aspect ........................................................................................ 191 Declaring a pointcut ........................................................................................ 192 Supported Pointcut Designators .............................................................. 192 Combining pointcut expressions .............................................................. 194 Sharing common pointcut definitions ........................................................ 194 Examples ............................................................................................... 196 Writing good pointcuts ............................................................................ 198 Declaring advice ............................................................................................. 199 Before advice ......................................................................................... 199 After returning advice .............................................................................. 200 After throwing advice .............................................................................. 200 After (finally) advice ................................................................................ 201 Around advice ........................................................................................ 202 Advice parameters .................................................................................. 203 Advice ordering ...................................................................................... 206 Introductions ................................................................................................... 206 Aspect instantiation models ............................................................................. 207 Example ......................................................................................................... 208 8.3. Schema-based AOP support ............................................................................ 209 Declaring an aspect ........................................................................................ 210 Declaring a pointcut ........................................................................................ 210 Declaring advice ............................................................................................. 212 Before advice ......................................................................................... 212 After returning advice .............................................................................. 212 After throwing advice .............................................................................. 213 After (finally) advice ................................................................................ 214 Around advice ........................................................................................ 214 Advice parameters .................................................................................. 215 Advice ordering ...................................................................................... 216 Introductions ................................................................................................... 217 Aspect instantiation models ............................................................................. 217 Advisors ......................................................................................................... 217 Example ......................................................................................................... 218 8.4. Choosing which AOP declaration style to use .................................................... 220 Spring AOP or full AspectJ? ........................................................................... 220 @AspectJ or XML for Spring AOP? ................................................................. 221 8.5. Mixing aspect types ......................................................................................... 222 8.6. Proxying mechanisms ...................................................................................... 222 Understanding AOP proxies ............................................................................ 223 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation viii 8.7. Programmatic creation of @AspectJ Proxies ..................................................... 225 8.8. Using AspectJ with Spring applications ............................................................. 225 Using AspectJ to dependency inject domain objects with Spring ........................ 226 Unit testing @Configurable objects .......................................................... 228 Working with multiple application contexts ................................................ 228 Other Spring aspects for AspectJ .................................................................... 229 Configuring AspectJ aspects using Spring IoC ................................................. 229 Load-time weaving with AspectJ in the Spring Framework ................................. 230 A first example ....................................................................................... 231 Aspects .................................................................................................. 234 ' META-INF/aop.xml' ............................................................................... 234 Required libraries (JARS) ........................................................................ 234 Spring configuration ................................................................................ 235 Environment-specific configuration ........................................................... 237 8.9. Further Resources ........................................................................................... 239 9. Spring AOP APIs ....................................................................................................... 240 9.1. Introduction ..................................................................................................... 240 9.2. Pointcut API in Spring ...................................................................................... 240 Concepts ........................................................................................................ 240 Operations on pointcuts .................................................................................. 241 AspectJ expression pointcuts .......................................................................... 241 Convenience pointcut implementations ............................................................ 241 Static pointcuts ....................................................................................... 241 Dynamic pointcuts .................................................................................. 242 Pointcut superclasses ..................................................................................... 243 Custom pointcuts ............................................................................................ 243 9.3. Advice API in Spring ........................................................................................ 243 Advice lifecycles ............................................................................................. 243 Advice types in Spring .................................................................................... 244 Interception around advice ...................................................................... 244 Before advice ......................................................................................... 244 Throws advice ........................................................................................ 245 After Returning advice ............................................................................ 246 Introduction advice .................................................................................. 247 9.4. Advisor API in Spring ....................................................................................... 249 9.5. Using the ProxyFactoryBean to create AOP proxies ........................................... 250 Basics ............................................................................................................ 250 JavaBean properties ....................................................................................... 250 JDK- and CGLIB-based proxies ...................................................................... 251 Proxying interfaces ......................................................................................... 252 Proxying classes ............................................................................................ 254 Using global advisors ...................................................................................... 255 9.6. Concise proxy definitions ................................................................................. 255 9.7. Creating AOP proxies programmatically with the ProxyFactory ............................ 256 9.8. Manipulating advised objects ............................................................................ 257 9.9. Using the "auto-proxy" facility ........................................................................... 258 Autoproxy bean definitions .............................................................................. 258 BeanNameAutoProxyCreator ................................................................... 259 DefaultAdvisorAutoProxyCreator .............................................................. 259 AbstractAdvisorAutoProxyCreator ............................................................ 260 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation ix Using metadata-driven auto-proxying ............................................................... 260 9.10. Using TargetSources ...................................................................................... 262 Hot swappable target sources ......................................................................... 263 Pooling target sources .................................................................................... 263 Prototype target sources ................................................................................. 265 ThreadLocal target sources ............................................................................. 265 9.11. Defining new Advice types ............................................................................. 265 9.12. Further resources ........................................................................................... 266 10. Testing ..................................................................................................................... 267 10.1. Introduction to Spring Testing ......................................................................... 267 10.2. Unit Testing ................................................................................................... 267 Mock Objects ................................................................................................. 267 Environment ........................................................................................... 267 JNDI ...................................................................................................... 267 Servlet API ............................................................................................. 267 Portlet API ............................................................................................. 268 Unit Testing support Classes .......................................................................... 268 General utilities ...................................................................................... 268 Spring MVC ........................................................................................... 268 10.3. Integration Testing ......................................................................................... 268 Overview ........................................................................................................ 268 Goals of Integration Testing ............................................................................ 269 Context management and caching ........................................................... 269 Dependency Injection of test fixtures ....................................................... 269 Transaction management ........................................................................ 270 Support classes for integration testing ..................................................... 270 JDBC Testing Support .................................................................................... 271 Annotations .................................................................................................... 271 Spring Testing Annotations ..................................................................... 271 Standard Annotation Support .................................................................. 276 Spring JUnit Testing Annotations ............................................................. 277 Meta-Annotation Support for Testing ........................................................ 278 Spring TestContext Framework ....................................................................... 279 Key abstractions ..................................................................................... 280 Context management .............................................................................. 281 Dependency injection of test fixtures ........................................................ 297 Testing request and session scoped beans .............................................. 299 Transaction management ........................................................................ 301 TestContext Framework support classes .................................................. 304 Spring MVC Test Framework .......................................................................... 306 Server-Side Tests ................................................................................... 306 Client-Side REST Tests .......................................................................... 312 PetClinic Example .......................................................................................... 313 10.4. Further Resources ......................................................................................... 314 IV. Data Access ..................................................................................................................... 316 11. Transaction Management .......................................................................................... 317 11.1. Introduction to Spring Framework transaction management .............................. 317 11.2. Advantages of the Spring Framework’s transaction support model ..................... 317 Global transactions ......................................................................................... 317 Local transactions ........................................................................................... 318 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation x Spring Framework’s consistent programming model ......................................... 318 11.3. Understanding the Spring Framework transaction abstraction ............................ 319 11.4. Synchronizing resources with transactions ....................................................... 323 High-level synchronization approach ................................................................ 323 Low-level synchronization approach ................................................................. 323 TransactionAwareDataSourceProxy ................................................................. 324 11.5. Declarative transaction management ............................................................... 324 Understanding the Spring Framework’s declarative transaction implementation ... 325 Example of declarative transaction implementation ........................................... 326 Rolling back a declarative transaction .............................................................. 330 Configuring different transactional semantics for different beans ........................ 331 settings ....................................................................................... 333 Using @Transactional ..................................................................................... 335 @Transactional settings .......................................................................... 339 Multiple Transaction Managers with @Transactional ................................. 340 Custom shortcut annotations ................................................................... 341 Transaction propagation .................................................................................. 341 Required ................................................................................................ 342 RequiresNew .......................................................................................... 342 Nested ................................................................................................... 343 Advising transactional operations ..................................................................... 343 Using @Transactional with AspectJ ................................................................. 346 11.6. Programmatic transaction management ........................................................... 347 Using the TransactionTemplate ....................................................................... 347 Specifying transaction settings ................................................................ 349 Using the PlatformTransactionManager ............................................................ 349 11.7. Choosing between programmatic and declarative transaction management ........ 350 11.8. Application server-specific integration .............................................................. 350 IBM WebSphere ............................................................................................. 351 Oracle WebLogic Server ................................................................................. 351 11.9. Solutions to common problems ....................................................................... 351 Use of the wrong transaction manager for a specific DataSource ....................... 351 11.10. Further Resources ....................................................................................... 351 12. DAO support ............................................................................................................ 352 12.1. Introduction .................................................................................................... 352 12.2. Consistent exception hierarchy ....................................................................... 352 12.3. Annotations used for configuring DAO or Repository classes ............................ 353 13. Data access with JDBC ............................................................................................ 355 13.1. Introduction to Spring Framework JDBC .......................................................... 355 Choosing an approach for JDBC database access ........................................... 355 Package hierarchy .......................................................................................... 356 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ................................................................................................................. 357 JdbcTemplate ................................................................................................. 357 Examples of JdbcTemplate class usage ................................................... 357 JdbcTemplate best practices ................................................................... 359 NamedParameterJdbcTemplate ....................................................................... 361 SQLExceptionTranslator .................................................................................. 363 Executing statements ...................................................................................... 365 Running queries ............................................................................................. 365 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xi Updating the database .................................................................................... 366 Retrieving auto-generated keys ....................................................................... 367 13.3. Controlling database connections .................................................................... 367 DataSource .................................................................................................... 367 DataSourceUtils .............................................................................................. 369 SmartDataSource ........................................................................................... 369 AbstractDataSource ........................................................................................ 369 SingleConnectionDataSource .......................................................................... 369 DriverManagerDataSource .............................................................................. 369 TransactionAwareDataSourceProxy ................................................................. 370 DataSourceTransactionManager ...................................................................... 370 NativeJdbcExtractor ........................................................................................ 370 13.4. JDBC batch operations .................................................................................. 371 Basic batch operations with the JdbcTemplate ................................................. 371 Batch operations with a List of objects ............................................................. 372 Batch operations with multiple batches ............................................................ 373 13.5. Simplifying JDBC operations with the SimpleJdbc classes ................................ 374 Inserting data using SimpleJdbcInsert .............................................................. 374 Retrieving auto-generated keys using SimpleJdbcInsert .................................... 375 Specifying columns for a SimpleJdbcInsert ...................................................... 376 Using SqlParameterSource to provide parameter values ................................... 376 Calling a stored procedure with SimpleJdbcCall ............................................... 377 Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 379 How to define SqlParameters .......................................................................... 380 Calling a stored function using SimpleJdbcCall ................................................. 381 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 381 13.6. Modeling JDBC operations as Java objects ..................................................... 382 SqlQuery ........................................................................................................ 383 MappingSqlQuery ........................................................................................... 383 SqlUpdate ...................................................................................................... 384 StoredProcedure ............................................................................................. 385 13.7. Common problems with parameter and data value handling .............................. 388 Providing SQL type information for parameters ................................................. 389 Handling BLOB and CLOB objects .................................................................. 389 Passing in lists of values for IN clause ............................................................ 390 Handling complex types for stored procedure calls ........................................... 391 13.8. Embedded database support .......................................................................... 392 Why use an embedded database? .................................................................. 392 Creating an embedded database instance using Spring XML ............................ 392 Creating an embedded database instance programmatically .............................. 392 Extending the embedded database support ...................................................... 393 Using HSQL ................................................................................................... 393 Using H2 ........................................................................................................ 393 Using Derby ................................................................................................... 393 Testing data access logic with an embedded database ..................................... 393 13.9. Initializing a DataSource ................................................................................. 394 Initializing a database instance using Spring XML ............................................. 394 Initialization of Other Components that Depend on the Database ............... 395 14. Object Relational Mapping (ORM) Data Access .......................................................... 397 14.1. Introduction to ORM with Spring ..................................................................... 397 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xii 14.2. General ORM integration considerations ......................................................... 398 Resource and transaction management ........................................................... 398 Exception translation ....................................................................................... 399 14.3. Hibernate ....................................................................................................... 399 SessionFactory setup in a Spring container ...................................................... 400 Implementing DAOs based on plain Hibernate 3 API ........................................ 400 Declarative transaction demarcation ................................................................ 402 Programmatic transaction demarcation ............................................................ 404 Transaction management strategies ................................................................ 405 Comparing container-managed and locally defined resources ............................ 407 Spurious application server warnings with Hibernate ......................................... 408 14.4. JDO .............................................................................................................. 409 PersistenceManagerFactory setup ................................................................... 409 Implementing DAOs based on the plain JDO API ............................................. 410 Transaction management ................................................................................ 412 JdoDialect ...................................................................................................... 413 14.5. JPA ............................................................................................................... 414 Three options for JPA setup in a Spring environment ........................................ 414 LocalEntityManagerFactoryBean .............................................................. 414 Obtaining an EntityManagerFactory from JNDI ......................................... 415 LocalContainerEntityManagerFactoryBean ............................................... 415 Dealing with multiple persistence units ..................................................... 417 Implementing DAOs based on plain JPA .......................................................... 418 Transaction Management ................................................................................ 420 JpaDialect ...................................................................................................... 421 15. Marshalling XML using O/X Mappers ......................................................................... 423 15.1. Introduction .................................................................................................... 423 Ease of configuration ...................................................................................... 423 Consistent Interfaces ...................................................................................... 423 Consistent Exception Hierarchy ....................................................................... 423 15.2. Marshaller and Unmarshaller .......................................................................... 423 Marshaller ...................................................................................................... 423 Unmarshaller .................................................................................................. 424 XmlMappingException ..................................................................................... 425 15.3. Using Marshaller and Unmarshaller ................................................................. 425 15.4. XML Schema-based Configuration .................................................................. 427 15.5. JAXB ............................................................................................................. 427 Jaxb2Marshaller ............................................................................................. 428 XML Schema-based Configuration ........................................................... 428 15.6. Castor ........................................................................................................... 429 CastorMarshaller ............................................................................................ 429 Mapping ......................................................................................................... 429 XML Schema-based Configuration ........................................................... 429 15.7. XMLBeans ..................................................................................................... 430 XmlBeansMarshaller ....................................................................................... 430 XML Schema-based Configuration ........................................................... 430 15.8. JiBX .............................................................................................................. 431 JibxMarshaller ................................................................................................ 431 XML Schema-based Configuration ........................................................... 431 15.9. XStream ........................................................................................................ 432 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xiii XStreamMarshaller ......................................................................................... 432 V. The Web ........................................................................................................................... 434 16. Web MVC framework ................................................................................................ 435 16.1. Introduction to Spring Web MVC framework .................................................... 435 Features of Spring Web MVC ......................................................................... 436 Pluggability of other MVC implementations ...................................................... 437 16.2. The DispatcherServlet .................................................................................... 437 Special Bean Types In the WebApplicationContext ........................................... 440 Default DispatcherServlet Configuration ........................................................... 441 DispatcherServlet Processing Sequence .......................................................... 441 16.3. Implementing Controllers ................................................................................ 443 Defining a controller with @Controller .............................................................. 443 Mapping Requests With Using @RequestMapping ........................................... 444 New Support Classes for @RequestMapping methods in Spring MVC 3.1 .. 446 URI Template Patterns ........................................................................... 447 URI Template Patterns with Regular Expressions ..................................... 448 Path Patterns ......................................................................................... 449 Patterns with Placeholders ...................................................................... 449 Matrix Variables ...................................................................................... 449 Consumable Media Types ....................................................................... 450 Producible Media Types .......................................................................... 451 Request Parameters and Header Values ................................................. 451 Defining @RequestMapping handler methods .................................................. 452 Supported method argument types .......................................................... 452 Supported method return types ............................................................... 454 Binding request parameters to method parameters with @RequestParam ... 455 Mapping the request body with the @RequestBody annotation .................. 456 Mapping the response body with the @ResponseBody annotation ............. 457 Creating REST Controllers with the @RestController annotation ................ 457 Using HttpEntity ...................................................................................... 457 Using @ModelAttribute on a method ....................................................... 458 Using @ModelAttribute on a method argument ......................................... 459 Using @SessionAttributes to store model attributes in the HTTP session between requests ................................................................................... 461 Specifying redirect and flash attributes ..................................................... 461 Working with "application/x-www-form-urlencoded" data ............................ 462 Mapping cookie values with the @CookieValue annotation ........................ 462 Mapping request header attributes with the @RequestHeader annotation ... 463 Method Parameters And Type Conversion ............................................... 463 Customizing WebDataBinder initialization ................................................. 464 Support for the Last-Modified Response Header To Facilitate Content Caching ................................................................................................. 465 Assisting Controllers with the @ControllerAdvice annotation ...................... 465 Asynchronous Request Processing .................................................................. 466 Exception Handling for Async Requests ................................................... 467 Intercepting Async Requests ................................................................... 467 Configuration for Async Request Processing ............................................ 468 Testing Controllers ......................................................................................... 469 16.4. Handler mappings .......................................................................................... 469 Intercepting requests with a HandlerInterceptor ................................................ 469 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation xiv 16.5. Resolving views ............................................................................................. 471 Resolving views with the ViewResolver interface .............................................. 471 Chaining ViewResolvers ................................................................................. 473 Redirecting to views ....................................................................................... 474 RedirectView .......................................................................................... 474 The redirect: prefix ................................................................................. 475 The forward: prefix ................................................................................. 475 ContentNegotiatingViewResolver ..................................................................... 475 16.6. Using flash attributes ..................................................................................... 478 16.7. Building URIs ................................................................................................. 479 16.8. Building URIs to Controllers and methods ....................................................... 480 16.9. Using locales ................................................................................................. 480 Obtaining Time Zone Information .................................................................... 481 AcceptHeaderLocaleResolver .......................................................................... 481 CookieLocaleResolver ..................................................................................... 481 SessionLocaleResolver ................................................................................... 481 LocaleChangeInterceptor ................................................................................ 482 16.10. Using themes ............................................................................................... 482 Overview of themes ........................................................................................ 482 Defining themes ............................................................................................. 482 Theme resolvers ............................................................................................. 483 16.11. Spring’s multipart (file upload) support ........................................................... 483 Introduction .................................................................................................... 483 Using a MultipartResolver with Commons FileUpload ........................................ 484 Using a MultipartResolver with Servlet 3.0 ....................................................... 484 Handling a file upload in a form ...................................................................... 484 Handling a file upload request from programmatic clients .................................. 486 16.12. Handling exceptions ..................................................................................... 486 HandlerExceptionResolver ............

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧