锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
processing and error handling
11.2.1.
鍒涘緩鏁版嵁婧愶紙鏁版嵁婧愰噷闅愯棌浜嗘暟鎹繛鎺ユ睜錛?BR>DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "org.hsqldb.jdbcDriver");
dataSource.setUrl( "jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername( "sa");
dataSource.setPassword( "");
11.2.3. SQLExceptionTranslator
閰嶇疆JdbcTemplate鍙婂紓甯稿鐞?BR> // create a JdbcTemplate and set data source
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
// create a custom translator and set the datasource for the default translation lookup
MySQLErrorCodesTransalator tr = new MySQLErrorCodesTransalator();
tr.setDataSource(dataSource);
jt.setExceptionTranslator(tr);
// use the JdbcTemplate for this SqlUpdate
SqlUpdate su = new SqlUpdate();
su.setJdbcTemplate(jt);
su.setSql("update orders set shipping_charge = shipping_charge * 1.05");
su.compile();
su.update();
11.2.4 綆鍗曠殑璋冪敤閰嶇疆濂戒簡鐨凧dbcTemplate灝卞彲浠ユ墽琛孲QL璇彞 濡備笅
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAStatement {
private JdbcTemplate jt;
private DataSource dataSource;
public void doExecute() {
jt = new JdbcTemplate(dataSource);
jt.execute("create table mytable (id integer, name varchar(100))");
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
11.2.5. 鎵ц鏌ヨ璇彞
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class RunAQuery {
private JdbcTemplate jt;
private DataSource dataSource;
public int getCount() {
jt = new JdbcTemplate(dataSource);
int count = jt.queryForInt("select count(*) from mytable");
return count;
}
public String getName() {
jt = new JdbcTemplate(dataSource);
String name = (String) jt.queryForObject("select name from mytable", String.class);
錛堟敞錛氬鏋滄洿鏂拌鍙ュ氨涔﹀啓jt.update("update mytable set name = ? where id = ?", new Object[] {name, new Integer(id)});錛?BR> return name;
}鈶?/FONT>
public List getList() {
jt = new JdbcTemplate(dataSource);
List rows = jt.queryForList("select * from mytable");
return rows;
}鈶?nbsp; 錛堚憼鈶″彇鍏朵竴錛?BR>
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
The PlatformTransactionManager definition will look like this:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
浣跨敤JTA浜嬪姟綆$悊鍣?BR>If we use JTA, as in the dataAccessContext-jta.xml file from the same sample application, we need to use a
container DataSource, obtained via JNDI, and a JtaTransactionManager implementation. The
JtaTransactionManager doesn't need to know about the DataSource, or any other specific resources, as it will
use the container's global transaction management.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/jpetstore"/>>
</bean>
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
浠ヤ笂涓ょ鏂規硶瀹炵幇鐨勫姛鑳芥槸絳夋晥鐨勩?/FONT>
2銆傛妸hibernate鍜宻pring緇撳悎璧鋒潵
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">鈶狅紙灞閮ㄤ簨鍔★級
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
鈶犲With Hibernate and JTA transactions we could simply use the JtaTransactionManager as with JDBC or any
other resource strategy.
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>錛圝TA涓哄叏灞浜嬪姟錛?/FONT>
澹版槑寮忎簨鍔$鐞?BR><!-- this example is in verbose form, see note later about concise for multiple proxies! -->
<!-- the target bean to wrap transactionally -->
<bean id="petStoreTarget">
...
</bean>
<bean id="petStore" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="txManager"/>
<property name="target" ref="petStoreTarget"/>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED,-MyCheckedException</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
閰嶇疆bean鐨刋ML鍑犵鏍煎紡濡備笅錛?BR> (1)銆傞氳繃鏋勯犲嚱鏁板垱寤篵ean錛宐ean鍙互鏄痡avabean 涔熷彲浠ヤ笉鏄紝涔熶笉鐢ㄥ疄鐜板埆鐨勬帴鍙c?BR> <bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
濡傛灉浣犻渶瑕佸疄鐜癐OC鏈哄埗錛屼綘鐨刡ean闇瑕佷竴涓粯璁ょ殑絀哄弬鏁版瀯閫犲嚱鏁般?BR> (2)銆傞氳繃闈欐佸伐鍘傚嚱鏁板垱寤篵ean.
<bean id="exampleBean" class="examples.ExampleBean2"
factory-method="createInstance"/>
createInstance鏄痚xamples.ExampleBean2鐨勯潤鎬佸伐鍘傛柟娉曪紝鐢ㄤ簬鐢熸垚exampleBean銆?BR> (3).閫氳繃瀹炰緥宸ュ巶鏂規硶鍒涘緩bean.
<!-- The factory bean, which contains a method called createInstance -->
<bean id="myFactoryBean" class="...">
...
</bean>
<!-- The bean to be created via the factory bean -->
<bean id="exampleBean" factory-bean="myFactoryBean" factory-method="createInstance"/>
To singleton or not to singleton
<bean id="exampleBean"
class="examples.ExampleBean" singleton="false"/>
<bean name="yetAnotherExample"
class="examples.ExampleBeanTwo" singleton="true"/>
鍑犵渚濊禆娉ㄥ皠鏍煎紡
(1)setter娉ㄥ皠
<bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty"><value>1</value></property>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
public void setIntegerProperty(int i) {
this.i = i;
}
}
(2)鏋勯犲嚱鏁版敞灝?BR><bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg type="int"><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
this.beanOne = anotherBean;
this.beanTwo = yetAnotherBean;
this.i = i;
}
}
(3)闈欐佸伐鍘傛敞灝?BR><bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {
...
// a private constructor
private ExampleBean(...) {
...
}
// a static factory method
// the arguments to this method can be considered the dependencies of the bean that
// is returned, regardless of how those arguments are actually used.
public static ExampleBean createInstance(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
ExampleBean eb = new ExampleBean(...);
// some other operations
...
return eb;
}
}
鏋勯犲嚱鏁伴厤緗殑鍙︿竴縐嶆牸寮?BR><bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0"><value>7500000</value></constructor-arg>
<constructor-arg index="1"><value>42</value></constructor-arg>
</bean>
鍙互鍦ㄩ厤緗枃浠朵腑鍔犲叆楠岃瘉鏁版嵁鐨勭被鍨?濡備笅
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" type="int"><value>7500000</value></constructor-arg>
<constructor-arg index="1" type="java.lang.String"><value>42</value></constructor-arg>
</bean>
涓鑸睘鎬ч厤緗牸寮?BR><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/mydb</value>
</property>
<property name="username">
<value>root</value>
</property>
</bean>
娉ㄦ剰錛?lt;value></value> 榛樿涓虹┖瀛楃涓詫紝
灞炴ull鐨勬牸寮忓涓?BR><bean class="ExampleBean">
<property name="email"><null/></property>
</bean>
灞炴ollection鐨勬牸寮忓涓?BR><bean id="moreComplexObject" class="example.ComplexObject">
<!-- results in a setPeople(java.util.Properties) call -->
<property name="people">
<props>
<prop key="HarryPotter">The magic property</prop>
<prop key="JerrySeinfeld">The funny property</prop>
</props>
</property>
<!-- results in a setSomeList(java.util.List) call -->
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource"/>
</list>
</property>
<!-- results in a setSomeMap(java.util.Map) call -->
<property name="someMap">
<map>
<entry>
<key><value>yup an entry</value></key>
<value>just some string</value>
</entry>
<entry>
<key><value>yup a ref</value></key>
<ref bean="myDataSource"/>
</entry>
</map>
</property>
<!-- results in a setSomeSet(java.util.Set) call -->
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource"/>
</set>
</property>
</bean>
3.3.3.4. Inner bean definitions via nested bean elements
<bean id="outer" class="...">
<!-- Instead of using a reference to target, just use an inner bean -->
<property name="target">
<bean class="com.mycompany.PersonImpl">//宓屽鐨刡ean涓嶉渶瑕乮d
<property name="name"><value>Tony</value></property>
<property name="age"><value>51</value></property>
</bean>
</property>
</bean>
澶嶅悎灞炴у畾涔?BR><bean id="foo" class="foo.Bar">
<property name="fred.bob.sammy" value="123"/> 灞炴red涓嬫湁灞炴ob,bob灞炴т笅鏈塻ammy 鎶妔ammy緗負123銆?BR></bean>
3.3.4. Method Injection錛堟柟娉曟敞灝勶級
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="singleShotHelper class="..." singleton="false">
</bean>
<!-- myBean uses singleShotHelper -->
<bean id="myBean" class="...">
<lookup-method name="createSingleShotHelper" bean="singleShotHelper"/>
<property>
...
</property>
</bean>
鎴戠殑鐞嗚В錛歮yBean 涓繀欏誨疄鐜?protected [abstract] SingleShotHelper createSingleShotHelper();
singleShotHelper涓繀欏誨疄鐜?protected SingleShotHelper createSingleShotHelper();
榪愯鏃?nbsp; singleShotHelper鐨刢reateSingleShotHelper浼氳鐩杕yBean鐨刢reateSingleShotHelper銆?/鏈獙璇?/FONT>
3.3.4.2. Arbitrary method replacement錛堜換鎰忕殑鏂規硶鏇挎崲錛?BR>public class MyValueCalculator {
public String computeValue(String input) {
... some real code
}
... some other methods
}
榪涜鏇挎崲鐨勭被蹇呴』瀹炵幇鎺ュ彛org.springframework.beans.factory.support.MethodReplacer
public class ReplacementComputeValue implements MethodReplacer {
public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
// get the input value, work with it, and return a computed result
String input = (String) args[0];
...
return ...;
}
}
<bean id="myValueCalculator class="x.y.z.MyValueCalculator">
<!-- arbitrary method replacement -->
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>String</arg-type> 榪欓噷琛ㄧず鏂規硶鎺ュ彈鐨勫弬鏁幫紝鏈夊嚑涓垪鍑犱釜銆?BR> </replaced-method> 榪欐牱myValueCalculator涓殑computeValue鏂規硶灝辮鏇挎崲浜?BR></bean>
<bean id="replacementComputeValue" class="a.b.c.ReplaceMentComputeValue"/>
3.4.1鐢熷懡鍛ㄦ湡
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
Is exactly the same as:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like closing connection)
}
}
Is exactly the same as:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work
}
}
===============================================
3.7. 鐢˙eanPostProcessors鑷畾涔塨eans
ConfigurableBeanFactory bf = new .....; // create BeanFactory
... // now register some beans
// now register any needed BeanPostProcessors
MyBeanPostProcessor pp = new MyBeanPostProcessor();
bf.addBeanPostProcessor(pp);
// now start using the factory
3.8. 鐢˙eanFactoryPostProcessors 鑷畾涔塨ean factories
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
// create placeholderconfigurer to bring in some property
// values from a Properties file
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
// now actually do the replacement
cfg.postProcessBeanFactory(factory);
錛堜篃鍙互澹版槑寮忓畾涔?BR> <!-- property placeholder post-processor -->
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="jdbc.properties"/>
</bean>
錛?/FONT>
鐢變笂
浠ヤ笅榪欎釜澶勪簬beanfactory瀹瑰櫒閲岀殑鏁版嵁婧愬氨鎸塲dbc.properties閲岀殑閰嶇疆浜?BR><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
鍏朵腑jdbc.properties濡備笅
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
3.8.2. The PropertyOverrideConfigurer
3.19. Creating an ApplicationContext from a web application
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>錛坱he listener cannot be used in Servlet 2.2 compatible
containers 浣嗘槸鍦⊿ervlet2.4鍚庨兘鏅亶閲囩敤瀹冿級
<!-- OR USE THE CONTEXTLOADERSERVLET INSTEAD OF THE LISTENER
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->