??xml version="1.0" encoding="utf-8" standalone="yes"?>
PreparedStatement stmt=conn.prepareStatement(
"update account set balance=? where acct_id=?");
int[] rows;
for(int i=0;i<accts.length;i++){
stmt.setInt(1,i);
stmt.setLong(2,i);
stmt.addBatch();
}
rows=stemt.executeBatch();
select * from (select rownum as numrow from table_name where numrow>80 and numrow<100 )
不能直接使用 select * from rownum>100 and rownum<200;
in oracle return null;
2 sql server 的实?br />3 mysql 的实?/p>
select id from table_name where id in
select * from (select rownum as numrow ,id from tabl_name)
where numrow>80 and num<100;
使用存储q程
单的老的JDBC通过CallableStatementcL持存储过E的调用。该cd际上是PreparedStatement的一个子cR假设我们有一个poets数据库。数据库中有一个设|诗人逝世q龄的存储过E。下面是对老酒鬼Dylan ThomasQold soak Dylan ThomasQ不指定是否有关典故、文化,h评指正。译注)q行调用的详l代码:
try{
int age = 39;
String poetName = "dylan thomas";
CallableStatement proc = connection.prepareCall("{ call set_death_age(?, ?) }");
proc.setString(1, poetName);
proc.setInt(2, age);
cs.execute();
}catch (SQLException e){ // ....}
传给prepareCallҎ的字串是存储q程调用的书写规范。它指定了存储过E的名称Q?代表了你需要指定的参数?
和JDBC集成是存储过E的一个很大的便利Qؓ了从应用中调用存储过E,不需要存根(stubQ类或者配|文Ӟ除了你的DBMS的JDBC驱动E序外什么也不需要?
当这D代码执行时Q数据库的存储过E就被调用。我们没有去获取l果Q因存储q程q不q回l果。执行成功或p|通过例外得知。失败可能意味着调用存储q程时的p|Q比如提供的一个参数的cd不正)Q或者一个应用程序的p|Q比如抛Z个例外指C在poets数据库中q不存在“Dylan Thomas”)
l合SQL操作与存储过E?
映射Java对象到SQL表中的行相当单,但是通常需要执行几个SQL语句Q可能是一个SELECT查找IDQ然后一个INSERT插入指定ID的数据。在高度规格化(W合更高的范式,译注Q的数据库模式中Q可能需要多个表的更斎ͼ因此需要更多的语句。Java代码会很快地膨胀Q每一个语句的|络开销也迅速增加?
这些SQL语句转移C个存储过E中大大简化代码,仅涉及一ơ网l调用。所有关联的SQL操作都可以在数据库内部发生。ƈ且,存储q程语言Q例如PL/SQLQ允怋用SQL语法Q这比Java代码更加自然。下面是我们早期的存储过E,使用Oracle的PL/SQL语言~写Q?
create procedure set_death_age(poet VARCHAR2, poet_age NUMBER)
poet_id NUMBER;
begin SELECT id INTO poet_id FROM poets WHERE name = poet;
INSERT INTO deaths (mort_id, age) VALUES (poet_id, poet_age);
end set_death_age;
很独特?不。我打赌你一定期待看C个poets表上的UPDATE。这也暗CZ使用存储q程实现是多么容易的一件事情。set_death_age几乎可以肯定是一个很烂的实现。我们应该在poets表中d一列来存储逝世q龄。Java代码中ƈ不关心数据库模式是怎么实现的,因ؓ它仅调用存储q程。我们以后可以改变数据库模式以提高性能Q但是我们不必修Ҏ们代码?
下面是调用上面存储过E的Java代码Q?
public static void setDeathAge(Poet dyingBard, int age) throws SQLException{
Connection con = null;
CallableStatement proc = null;
try {
con = connectionPool.getConnection();
proc = con.prepareCall("{ call set_death_age(?, ?) }");
proc.setString(1, dyingBard.getName());
proc.setInt(2, age);
proc.execute();
}
finally {
try { proc.close(); }
catch (SQLException e) {}
con.close();
}
}
Z保可维护性,使用像这儿这LstaticҎ。这也得调用存储过E的代码集中在一个简单的模版代码中。如果你用到许多存储q程Q就会发C需要拷贝、粘贴就可以创徏新的Ҏ。因Z码的模版化,甚至也可以通过脚本自动生调用存储q程的代码?
Functions
存储q程可以有返回|所以CallableStatementcLcMgetResultSetq样的方法来获取q回倹{当存储q程q回一个值时Q你必须使用registerOutParameterҎ告诉JDBC驱动器该值的SQLcd是什么。你也必调整存储过E调用来指示该过E返回一个倹{?
下面接着上面的例子。这ơ我们查询Dylan Thomas逝世时的q龄。这ơ的存储q程使用PostgreSQL的pl/pgsqlQ?
create function snuffed_it_when (VARCHAR) returns integer ''declare
poet_id NUMBER;
poet_age NUMBER;
begin
--first get the id associated with the poet.
SELECT id INTO poet_id FROM poets WHERE name = $1;
--get and return the age.
SELECT age INTO poet_age FROM deaths WHERE mort_id = poet_id;
return age;
end;'' language ''pl/pgsql'';
另外Q注意pl/pgsql参数名通过Unix和DOS脚本?n语法引用。同Ӟ也注意嵌入的注释Q这是和Java代码相比的另一个优性。在Java中写q样的注释当然是可以的,但是看v来很凌ؕQƈ且和SQL语句pQ必d入到Java String中?
下面是调用这个存储过E的Java代码Q?
connection.setAutoCommit(false);
CallableStatement proc = connection.prepareCall("{ ? = call snuffed_it_when(?) }");
proc.registerOutParameter(1, Types.INTEGER);
proc.setString(2, poetName);
cs.execute();
int age = proc.getInt(2);
如果指定了错误的q回值类型会怎样Q那么,当调用存储过E时抛Z个RuntimeExceptionQ正如你在ResultSet操作中用了一个错误的cd所到的一栗?
复杂的返回?
关于存储q程的知识,很多人好像就熟悉我们所讨论的这些。如果这是存储过E的全部功能Q那么存储过E就不是其它q程执行机制的替换方案了。存储过E的功能比这强大得多?
当你执行一个SQL查询ӞDBMS创徏一个叫做cursorQ游标)的数据库对象Q用于在q回l果中P代每一行。ResultSet是当前时间点的游标的一个表C。这是Z么没有缓存或者特定数据库的支持,你只能在ResultSet中向前移动?
某些DBMS允许从存储过E中q回游标的一个引用。JDBCq不支持q个功能Q但是Oracle、PostgreSQL和DB2的JDBC驱动器都支持在ResultSet上打开到游标的指针QpointerQ?
设想列出所有没有活到退休年龄的诗hQ下面是完成q个功能的存储过E,q回一个打开的游标,同样也用PostgreSQL的pl/pgsql语言Q?
create procedure list_early_deaths () return refcursor as ''declare
toesup refcursor;
begin
open toesup for SELECT poets.name, deaths.age FROM poets, deaths -- all entries in deaths are for poets. -- but the table might become generic.
WHERE poets.id = deaths.mort_id AND deaths.age < 60;
return toesup;
end;'' language ''plpgsql'';
下面是调用该存储q程的JavaҎQ将l果输出到PrintWriterQ?
PrintWriter:
static void sendEarlyDeaths(PrintWriter out){
Connection con = null;
CallableStatement toesUp = null;
try {
con = ConnectionPool.getConnection();
// PostgreSQL needs a transaction to do this... con.
setAutoCommit(false); // Setup the call.
CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");
toesUp.registerOutParameter(1, Types.OTHER);
toesUp.execute();
ResultSet rs = (ResultSet) toesUp.getObject(1);
while (rs.next()) {
String name = rs.getString(1);
int age = rs.getInt(2);
out.println(name + " was " + age + " years old.");
}
rs.close();
}
catch (SQLException e) { // We should protect these calls. toesUp.close(); con.close();
}
}
因ؓJDBCq不直接支持从存储过E中q回游标Q我们用Types.OTHER来指C存储过E的q回cdQ然后调用getObject()Ҏq对q回D行强制类型{换?
q个调用存储q程的JavaҎ是mapping的一个好例子。Mapping是对一个集上的操作q行抽象的方法。不是在q个q程上返回一个集Q我们可以把操作传送进L行。本例中Q操作就是把ResultSet打印C个输出流。这是一个值得举例的很常用的例子,下面是调用同一个存储过E的另外一个方法实玎ͼ
public class ProcessPoetDeaths{
public abstract void sendDeath(String name, int age);
}
static void mapEarlyDeaths(ProcessPoetDeaths mapper){
Connection con = null;
CallableStatement toesUp = null;
try {
con = ConnectionPool.getConnection();
con.setAutoCommit(false);
CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");
toesUp.registerOutParameter(1, Types.OTHER);
toesUp.execute();
ResultSet rs = (ResultSet) toesUp.getObject(1);
while (rs.next()) {
String name = rs.getString(1);
int age = rs.getInt(2);
mapper.sendDeath(name, age);
}
rs.close();
} catch (SQLException e) { // We should protect these calls. toesUp.close();
con.close();
}
}
q允许在ResultSet数据上执行Q意的处理Q而不需要改变或者复制获取ResultSet的方法:
static void sendEarlyDeaths(final PrintWriter out){
ProcessPoetDeaths myMapper = new ProcessPoetDeaths() {
public void sendDeath(String name, int age) {
out.println(name + " was " + age + " years old.");
}
};
mapEarlyDeaths(myMapper);
}
q个Ҏ使用ProcessPoetDeaths的一个匿名实例调用mapEarlyDeaths。该实例拥有sendDeathҎ的一个实玎ͼ和我们上面的例子一L方式把结果写入到输出。当Ӟq个技巧ƈ不是存储q程Ҏ的,但是和存储过E中q回的ResultSetl合使用Q是一个非常强大的工具?
l论
存储q程可以帮助你在代码中分逻辑Q这基本上L有益的。这个分ȝ好处有:
• 快速创建应用,使用和应用一h变和改善的数据库模式?
• 数据库模式可以在以后改变而不影响Java对象Q当我们完成应用后,可以重新设计更好的模式?
• 存储q程通过更好的SQL嵌入使得复杂的SQL更容易理解?
• ~写存储q程比在Java中编写嵌入的SQL拥有更好的工PQ大部分~辑器都提供语法高亮Q?
• 存储q程可以在Q何SQL命o行中试Q这使得调试更加Ҏ?
q不是所有的数据库都支持存储q程Q但是存在许多很的实现Q包括免?开源的和非免费的,所以移植ƈ不是一个问题。Oracle、PostgreSQL和DB2都有cM的存储过E语aQƈ且有在线的社区很好地支持?
存储q程工具很多Q有像TOAD或TORAq样的编辑器、调试器和IDEQ提供了~写、维护PL/SQL或pl/pgsql的强大的环境?
存储q程实增加了你的代码的开销Q但是它们和大多数的应用服务器相比,开销得多。如果你的代码复杂到需要用DBMSQ我整个采用存储q程的方式?/p>
另外Q你不愿意你的DAO试代码每次都打开关系SessionQ因此,我们一般会采用OpenSessionInView模式?
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(); logger.debug("Opening Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { filterChain.doFilter(request, response); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); logger.debug("Closing Hibernate Session in OpenSessionInViewFilter"); closeSession(session, sessionFactory); } }
Z么绑定以后,可以防止每ơ不会新开一个Session呢?看看HibernateDaoSupport的情况:
publicfinal void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } protectedfinal HibernateTemplate getHibernateTemplate() { return hibernateTemplate; }
我们的DAO用这个templateq行操作Q?
publicabstract class BaseHibernateObjectDao extends HibernateDaoSupport implements BaseObjectDao {protected BaseEntityObject getByClassId(finallong id) { BaseEntityObject obj = (BaseEntityObject) getHibernateTemplate() .execute(new HibernateCallback() {
publicObject doInHibernate(Session session) throws HibernateException { return session.get(getPersistentClass(), newLong(id)); }
}); return obj; }
public void save(BaseEntityObject entity) { getHibernateTemplate().saveOrUpdate(entity); }
public void remove(BaseEntityObject entity) { try {
getHibernateTemplate().delete(entity); } catch (Exception e) { thrownew FlexEnterpriseDataAccessException(e); } }
public void refresh(final BaseEntityObject entity) { getHibernateTemplate().execute(new HibernateCallback() {
publicObject doInHibernate(Session session) throws HibernateException { session.refresh(entity); returnnull; }
}); }
public void replicate(finalObject entity) { getHibernateTemplate().execute(new HibernateCallback() {
publicObject doInHibernate(Session session) throws HibernateException { session.replicate(entity, ReplicationMode.OVERWRITE); returnnull; }
}); }
publicObject execute(HibernateCallback action) throws DataAccessException { Session session = (!this.allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(), false) : SessionFactoryUtils.getSession(getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator())); boolean existingTransaction = TransactionSynchronizationManager.hasResource(getSessionFactory()); if (!existingTransaction && getFlushMode() == FLUSH_NEVER) { session.setFlushMode(FlushMode.NEVER); } try { Object result = action.doInHibernate(session); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { // callback code threw application exception throw ex; } finally { SessionFactoryUtils.closeSessionIfNecessary( session, getSessionFactory()); } }
publicstatic void closeSessionIfNecessary(Session session, SessionFactory sessionFactory) throws CleanupFailureDataAccessException { if (session == null || TransactionSynchronizationManager.hasResource(sessionFactory)) { return; } logger.debug("Closing Hibernate session"); try { session.close(); } catch (JDBCException ex) { // SQLException underneath thrownew CleanupFailureDataAccessException( "Cannot close Hibernate session", ex.getSQLException()); } catch (HibernateException ex) { thrownew CleanupFailureDataAccessException( "Cannot close Hibernate session", ex); } }
使用同样的方法,q两个Interceptor可以用来解决问题。但是关键的不同之处在于Q它们的力度只能定义在DAO或业务方法上Q而不是在我们的TestҎ上,除非我们把它们应用到TestCase的方法上Q但你不大可能ؓTestCased义一个接口,然后把Interceptor应用到这个接口的某些Ҏ上。直接用HibernateTransactionManager也是一L。因此,如果我们有这L试Q?
Category parentCategory = new Category (); parentCategory.setName("parent"); dao.save(parentCategory);Category childCategory = new Category(); childCategory.setName("child");
parentCategory.addChild(childCategory); dao.save(childCategory);
Category savedParent = dao.getCategory("parent"); Category savedChild = (Category ) savedParent.getChildren().get(0); assertEquals(savedChild, childCategory);
一U方法是对TestCase应用Interceptor或者TransactionManagerQ但q个恐怕会造成很多ȝ。除非是使用增强方式的AOP.我前期采用这U方?Aspectwerkz)Q在Eclipse里面也跑得含好?
另一U方法是在TestCase的setup和teardown里面实现和Filter完全一L处理Q其他的TestCase都从q个TestCasel承Q这U方法是我目前所使用的?
Jolestar补充:openSessionInView的配|方?
<filter>
<filter-name>opensession</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>false</param-value>
</init-param>
</filter>
c Read-Only
If a transaction performs only read operation against the underlying datastore.when a transaction begin ,it only make sense to declare a transaction as read only on mehtods with
propagation behavior which start a new transaction.
Furthermore ,if you are Hibernate as persistence mechanism,declaring a transaction as read only will reult in Hibernate flush mode being set to FLUST_NEVER.this tell hibernate to avoid synchroniztion of objects with database.
d Transaction timeout
Suppose that your transaction becomes unexpectedly long-running transaction.Because transaction may invole locks on the underlying database.Instead of waiting it out ,you can delcare a transaction to automaitically roll back.
because timeout clock begin ticking when a transaction start. it only make sense to declare a transaction timeout on methods with propagation behavior that start a new transaction.
2) Declaring a simple transaction policy
<bean id="myTransactionAttribute"
class="org.springframework.transaction.interceptor.
DefaultTransactionAttribute">
<property name="propagationBehaviorName">
<value>PROPAGATION_REQUIRES_NEW</value>
</property>
<property name="isolationLevelName">
<value>ISOLATION_REPEATABLE_READ</value>
</property>
</bean>
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
MatchAlwaysTransactionAttributeSource">
<property name="transactionAttribute">
<ref bean="myTransactionAttribute"/>
</property>
</bean>
4 Declaring transactions by method name
1) Using NameMatchTransactionAttributeSource
The properties property of NameMatchTransactionAttributeSource maps mehtod to a transaction property descriptor. the property descriptor takes the following form:
Propagation,isolation,readOnly,-Exception,+Exception
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="enrollStudentInCourse">
PROPAGATION_REQUIRES_NEW
</prop>
</props>
</property>
</bean>
2) Specifying the transaction Isolation level
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="enrollStudentInCourse">
PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ
</prop>
</props>
</property>
</bean>
3) Using real-only transaction
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="getCompletedCourses">
PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,readOnly
</prop>
</props>
</property>
</bean>
4)Specifying rollback rules
You can sepcify that a transaction be rollback on specify checked exception
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="enrollStudentInCourse">
PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ,
-CourseException
</prop>
</props>
</property>
</bean>
Exception can be marked as negative(-) or postive(+)
Negative exception will trigger the roll back if the exception (or sublclass of it) is thrown.Postive exception on the other hand indicate that the transacton should be commit
even if the exception is thrown
5)Using wildcard matches
<bean id="transactionAttributeSource"
class="org.springframework.transaction.interceptor.
NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="get*">
PROPAGATION_SUPPORTS
</prop>
</props>
</property>
</bean>
6 Short-cut name match transaction
<bean id="courseService" class="org.springframework.transaction.
interceptor.TransactionProxyFactoryBean">
<property name="transactionProperties">
<props>
<prop key="enrollStudentInCourse">
PROPAGATION_REQUIRES_NEW
</prop>
</props>
</property>
</bean>
</props>
</property>
?br /> </bean>
and the last thing is whick map files is read
<bean id="sessionFactory" class="org.springframework.
orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>Student.hbm.xml</value>
<value>Course.hbm.xml</value>
?br /> </list>
</property>
?br /> </bean>
Now you have fully configured your sessionfactory ,so we need do create an object which we
will access hibernate. As we know, we will use a template class
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="courseDao" class="com.springinaction.
training.dao.hibernate.CourseDaoHibernate">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
</property>
</bean>
2 Accessing Hibernate through HibernatTemplate
The template-callback mechanism in Hibernatee is pretty simple.There is the HibernatTmpplate and one callback interface
public Student getStudent(final Integer id) {
return (Student) hibernateTemplate.execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
return session.load(Student.class, id);
}
});
The HibernateTemplate class provides some convience methods that implicit create a HibernateCallback instance:
(Student) hibernateTemplate.load(Student.class, id);
hibernateTemplate.update(student);
hibernateTemplate.find("from Student student " +
"where student.lastName = ?",
lastName, Hibernate.STRING);
3 Subclassing HibernateDaoSupport
public class StudentDaoHibernate extends HibernateDaoSupport
implements StudentDao {
?br /> }
getHibernateTemplate()
getSession()
~点Q内存中加蝲了大量数?br /> 执行了多ơupdate 语句
改进
Iterator customers=session.find("from Customer c where c.age>0");
while(customers.hasNext()){
Customer customer=(Customer)customers.next();
customer.setAge(customer.getAge()+1);
session.flush();
session.evict(customer);
}
tx.commit();
session.close();
遗留问题
执行了多ơupdate 语句
采用jdbc api q行调用
Connection con=session.connection();
PrepareStatement stmt=con.prepareStatement("update customers set age=age+1 where age>0");
stmt.executeUpdate();
tx.commit();
另外Q也可以调用底层的存储过E进行批量更?br /> create or replace procedure batchUpdateCustomer(p_age,in number) as
begin
update customer set age=age+1 where age>p_age;
end;
tx=session.beginTransaction();
Connection con=session.connection();
CallableStatement cstmt=con.prepareCall(batchUpdateCustomer);
cstmt.setInt(1,0);
cstmt.eqecuteUpdate();
tx.commit();
2) 扚w数据的删?br /> session.delete("from Customer c where c.age>0");
实际调用的过E?br /> session * from Customer where age>0;
在把所有数据加载到内存之后执行多条delete 语句
delete from customer where id=i;
.......................
改进办法采用jdbc api q行扚w数据的删?br />
tx=session.beginTransaction();
Connection con=session.connection();
con.execute("delete from customers where age>0");
tx.commit();
integer or int int or Integer INTEGER
long long or Long BIGINT
short short or Short SMALLINT
byte byte or Byte TINYINT
float float or Float FLOAT
double double or Double DOUBLE
big_decimal java.math.BigDecimal NUMBERBIC
character char java.lang.Character CHAR(1)
String
string String VARCHAR
boolean boolean or Boolean BIT
date java.util.Date DATE
java.sql.Date
time Date or java.sql.time TIME
timestamp Date or java.sql.Timestamp TIMESTAMP
binary byte[] blog blog
text String clob clog
serializable blog blog
clob java.sql.clob clob clob
blob java.sql.blob blog blob
contexts.Beyong there two basic types of contains .Srping come with sereral implementss of BeanFacotory and ApplicationContext.
1 introducing the BeanFactory
There are several implementations of BeanFactory in Spring .But the most userful one is XmlBeanFactory,whick loads
its bean based on the definitions contained in an xml file.
Creat a XmlBeanFactory BeanFactory factory=new XMLBeanFactory(new FileInputStream("beans.xml"));
But at that time ,the BeanFactory does not initialize the bean ,it is loaded lazliy.
Get the Bean :MyBean myBean=(MyBean)factory.getBean("myBean");
When getBean() is called ,the factory will instantiate the bean and being setting the bean using dependency injection.
2 Working with an application context
an ApplicationContextis prefered over a BeanFactory in nearly all application ,the only time you might consider using a BeanFactory
are in circumtance where resource s are scarce.
Amony the many implements of ApplicationContext are three that are commonly used:
ClassPathXmlApplicationContext,FileSystemXmpApplicationContext,XmlWebApplicationContext.
ApplicationContext context=new ClassPathXmlApplicationContext("foo.xml");
wiring the beans
<beans>
<bean id="foo" class="com.springinaction.Foo" />
</beans>
Prototyping vs.singleton
By default ,all Spring beans are singletons.When the container dispenses a bean it will always give the exact same instance of the
In this case ,you would want to define a prototype bean .Defining a prototype means that instead of defining a single bean.
<bean id="foo" class="com.springinaction.Foo" single/>on="false" />
Initialization and destruction
<bean id="foo" class="com.springinaction.Foo" init-method="setup" destory-method="teardown">
Injectiong dependencies via setter method
<bean id="foo" class="com.srpinginaction.Foo" >
<property name="name">Foo McFoo</value>
</bean>
Referencing other beans
<bean id="foo" class="com.springinaction.Foo">
<property name="bar" >
<ref bean="bar" />
</property>
</bean>
<bean id="bar" colass="com.srpinginaction.Bar" />
Inner beans
<bean id="courseService"
class="com.CourseWericeImpl">
<property nanme="studentService">
<bean
class="com....." />
</property>
</bean>
Wiring collections
1Wiring lists and arrays java.util.List
<property name="barList">
<list>
<value>bar1</value>
<ref bean="bar2"/>
</lsit>
</property>
2 Wiring set java.tuil.Set
<property name="barSet">
<set>
<value>bar1</value>
<ref bean="bar2" />
</set>
</property>
3 Wiring maps java.util.Map
<property name="barMap">
<ebtry key="key1">
<value>bar1</value>
</property>
4 Wiring propertyies
<property name="barProps">
<props>
<prop key="key1">bar1</prop>
<prop key="key2">bar2</prop>
</props>
</property>
5 Setting null values
<property name="foo"><null/><property>
injecting dependencies via constructor
<id="foo" class="com.springinaction.Foo">
<constructor-arg>
<value>42<value>( <ref bean="bar">)
</constructor-arg>
<bean id="foo" class="com.springinaction.Foo">
<constructor-arg>
<value>http://www.manning.com</value>
</constructor-arg>
<constructor-arg>
<value>http://www.manning.com</value>
</constructor-arg>
</bean>