一旦Struts的 Action交由Spring进行管理之后,默认情况下,Action是单例的。 这会带来一系列的问题。
- 单例的Action
在list中加一句话,打印当前Action对象
然后不停刷新System.out.println(this);
就可以看到,每次打印的对象,都是同一个对象,这表明Spring管理的bean是单例模式的。http://127.0.0.1:8080/ssh/listProduct
package com.how2java.action; import java.util.List; import com.how2java.dao.ProductDAO; import com.how2java.pojo.Product; public class ProductAction { ProductDAO pdao; List<Product> products; public String list() { System.out.println(this); products = pdao.find("from Product p"); return "listJsp"; } public ProductDAO getPdao() { return pdao; } public void setPdao(ProductDAO pdao) { this.pdao = pdao; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } }
- 非单例模式
为productActionBean增加一个属性scope="prototype" ,用于告知Spring,这个对象的管理,使用非单例模式
重启tomcat,不停的访问
可以观察到,每次访问都是不同的ProductAction对象了。http://127.0.0.1:8080/ssh/listProduct
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="productActionBean" scope="prototype" class="com.how2java.action.ProductAction"> <property name="pdao" ref="pdao" /> </bean> <bean name="pdao" class="com.how2java.dao.ProductDAO"> <property name="sessionFactory" ref="sf" /> </bean> <bean name="sf" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="ds" /> <property name="mappingResources"> <list> <value>com/how2java/pojo/Product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=false hbm2ddl.auto=update </value> </property> </bean> <bean name="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="admin" /> </bean> </beans>