- 浏览: 330975 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
di1984HIT:
学习了~
Spring scope="prototype" -
netkiller.github.com:
路还很长看看我的博客 http://netkiller.git ...
写博客是个好习惯 -
ooo456mmm:
JAVA 设计模式之——动态代理 -
hanmiao:
问题是这么问的:请使用 Java 的基本数据类型表示壹下单链表 ...
JAVA数据结构之——单链表的逆序 -
hanmiao:
谢谢,今天刚好有人问我这个问题,结果没有答上来,看了你这篇文章 ...
JAVA数据结构之——单链表的逆序
在用SSH开发项目的过程中,对于spring初始化bean这块:
显然,初始化的bean有三类:DAO、Service、Action。DAO和Service都是无状态的bean,多线程访问的时候不会出问题;而Action是有状态的。所谓有状态的bean,是bean中含有一些成员变量,按照我的理解,就是可以区分对象与对象。对于有成员变量的bean,在多个用户的访问中,可能会出现问题。具体可以见
http://blog.csdn.net/anyoneking/archive/2010/01/12/5182164.aspx
例:
DAO
package com.ultratech.omis.fa.dao; import java.util.Date; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.ultratech.base.framework.BaseDAO; import com.ultratech.omis.fa.bo.FaMaintain; /** * A data access object (DAO) providing persistence and search support for * FaMaintain entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see com.ultratech.omis.fa.bo.FaMaintain * @author MyEclipse Persistence Tools */ public class FaMaintainDAO extends BaseDAO { private static final Logger log = LoggerFactory .getLogger(FaMaintainDAO.class); // property constants public static final String EQUIP_ID = "equipId"; public static final String STATUS = "status"; public static final String CREATE_USER_ID = "createUserId"; public static final String CREATE_DEPT_ID = "createDeptId"; public static final String PRIORITY = "priority"; public static final String REPLACE = "replace"; public static final String MAINTAIN_DEPT_ID = "maintainDeptId"; public static final String MAINTAIN_USER_ID = "maintainUserId"; public static final String MEMO = "memo"; protected void initDao() { // do nothing } public void save(FaMaintain transientInstance) { log.debug("saving FaMaintain instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(FaMaintain persistentInstance) { log.debug("deleting FaMaintain instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public FaMaintain findById(java.lang.Long id) { log.debug("getting FaMaintain instance with id: " + id); try { FaMaintain instance = (FaMaintain) getHibernateTemplate().get( "com.ultratech.omis.fa.bo.FaMaintain", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(FaMaintain instance) { log.debug("finding FaMaintain instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding FaMaintain instance with property: " + propertyName + ", value: " + value); try { String queryString = "from FaMaintain as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByEquipId(Object equipId) { return findByProperty(EQUIP_ID, equipId); } public List findByStatus(Object status) { return findByProperty(STATUS, status); } public List findByCreateUserId(Object createUserId) { return findByProperty(CREATE_USER_ID, createUserId); } public List findByCreateDeptId(Object createDeptId) { return findByProperty(CREATE_DEPT_ID, createDeptId); } public List findByPriority(Object priority) { return findByProperty(PRIORITY, priority); } public List findByReplace(Object replace) { return findByProperty(REPLACE, replace); } public List findByMaintainDeptId(Object maintainDeptId) { return findByProperty(MAINTAIN_DEPT_ID, maintainDeptId); } public List findByMaintainUserId(Object maintainUserId) { return findByProperty(MAINTAIN_USER_ID, maintainUserId); } public List findByMemo(Object memo) { return findByProperty(MEMO, memo); } public List findAll() { log.debug("finding all FaMaintain instances"); try { String queryString = "from FaMaintain"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public FaMaintain merge(FaMaintain detachedInstance) { log.debug("merging FaMaintain instance"); try { FaMaintain result = (FaMaintain) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(FaMaintain instance) { log.debug("attaching dirty FaMaintain instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(FaMaintain instance) { log.debug("attaching clean FaMaintain instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static FaMaintainDAO getFromApplicationContext(ApplicationContext ctx) { return (FaMaintainDAO) ctx.getBean("FaMaintainDAO"); } }
Service
package com.ultratech.omis.fa.service; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.ultratech.base.framework.BaseService; import com.ultratech.base.framework.DetachedCriteriaBuilder; import com.ultratech.base.framework.PageMeta; import com.ultratech.base.framework.ServiceException; import com.ultratech.omis.fa.bo.FaMaintain; import com.ultratech.omis.fa.bo.FaMaterialIn; import com.ultratech.omis.fa.dao.FaMaintainDAO; public class MaintainService extends BaseService{ public FaMaintainDAO maintainDAO; public void saveMaintain(FaMaintain instance)throws ServiceException{ maintainDAO.attachDirty(instance); } public void deleteMMaintain(FaMaintain instance) throws ServiceException { maintainDAO.delete(instance); } public void deleteMaintainById(Long maintainIds[]) throws ServiceException{ FaMaintain instance = new FaMaintain(); DetachedCriteria criteria = DetachedCriteriaBuilder.build(instance); criteria.add(Restrictions.in("maintainId", maintainIds)); maintainDAO.getHibernateTemplate().deleteAll(maintainDAO.findByCriteria(criteria)); } public FaMaintain findMaintainById(Long maintainId)throws ServiceException{ return maintainDAO.findById(maintainId); } public List<FaMaintain> findMaintain(FaMaintain instance, PageMeta page) throws ServiceException{ DetachedCriteria criteria = DetachedCriteriaBuilder.build(instance); return this.findByPage(maintainDAO, criteria, page); } public List<FaMaintain> findMaintain(DetachedCriteria criteria, PageMeta page) throws ServiceException { criteria.addOrder(Order.asc("maintainId")); return this.findByPage(maintainDAO, criteria, page); } public int getCount(DetachedCriteria criteria) throws ServiceException{ return maintainDAO.findTotalByCriteria(criteria); } public FaMaintainDAO getMaintainDAO(){ return maintainDAO; } public void setMaintainDAO(FaMaintainDAO maintainDAO){ this.maintainDAO = maintainDAO; } }
Action
package com.ultratech.omis.fa.web; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.ConvertUtils; import org.apache.struts2.ServletActionContext; import com.ultratech.base.framework.BaseAction; import com.ultratech.base.framework.DetachedCriteriaBuilder; import com.ultratech.base.framework.ServiceException; import com.ultratech.base.util.BeanTools; import com.ultratech.base.util.Constants; import com.ultratech.base.util.StringTools; import com.ultratech.omis.fa.bo.FaEquipment; import com.ultratech.omis.fa.bo.FaMaintain; import com.ultratech.omis.fa.bo.FaMaintainLog; import com.ultratech.omis.fa.service.EquipmentService; import com.ultratech.omis.fa.service.MaintainLogService; import com.ultratech.omis.fa.service.MaintainService; import com.ultratech.omis.fnd.bo.FndUser; import com.ultratech.omis.fnd.web.UserUtil; //基本表中的维修人必填!! public class MaintainEditAction extends BaseAction{ private String maintainId; private String equipId; private String status;// private String createUserId; private String createDeptId; private String createDate; private String priority;/// private String replace;/// private String maintainDeptId;//从基本表信息取 private String maintainUserId; private String fixDate;//不填 private String fixMethod;//不填 private String memo; private FaEquipment faEquipment; private List<FaMaintainLog> maintainLogList; private MaintainService maintainService; private EquipmentService equipmentService; private MaintainLogService maintainLogService; public MaintainEditAction(MaintainService maintainService, EquipmentService equipmentService, MaintainLogService maintainLogService){ this.maintainService = maintainService; this.equipmentService = equipmentService; this.maintainLogService = maintainLogService; } public void prepare() throws Exception { clearErrorsAndMessages(); } public String save(){ FndUser user = this.getUser(); //保存维修记录及日志,更改基本表 FaMaintain instance = new FaMaintain(); FaMaintainLog log = new FaMaintainLog(); BeanTools.copyProperties(instance, this);//equipId try { FaEquipment old = equipmentService.FindEquipmentById(StringTools.parseLong(equipId)); old.setHealthStatus("01");//损坏 instance.setStatus("00");//报修 instance.setCreateDate(new Date()); instance.setCreateDeptId(user.getDeptId()); instance.setCreateUserId(user.getUserId()); instance.setMaintainDeptId(old.getMaintainDeptId()); instance.setMaintainUserId(old.getMaintainUserId()); instance.setFaEquipment(old); maintainService.saveMaintain(instance); //维修表 log.setMaintainId(instance.getMaintainId()); log.setCreateDeptId(user.getDeptId()); log.setCreateUserId(user.getUserId()); log.setCreateDate(new Date()); log.setMemo(memo); maintainLogService.saveMaintainLog(log);//报修日志 equipmentService.saveEquipment(old); //基本表 return SUCCESS; } catch (ServiceException ex) { ex.printStackTrace(); this.addActionError(ex.getMessage()); return INPUT; } } public boolean isModified() { try { FaMaintain old = maintainService.findMaintainById(StringTools.parseLong(maintainId)); if(old != null) { if( ((old.getFixMethod() != null) && old.getFixMethod().equals(fixMethod)) && ((old.getMaintainDeptId() == null && (maintainDeptId == null || maintainDeptId.equals(""))) || (old.getMaintainDeptId() != null && old.getMaintainDeptId().toString().equals(maintainDeptId))) && ((old.getMaintainUserId() == null && (maintainUserId == null || maintainUserId.equals(""))) || (old.getMaintainUserId() != null && old.getMaintainUserId().toString().equals(maintainUserId))) && ((old.getStatus() == null && (status == null || status.equals(""))) || (old.getStatus() != null && old.getStatus().toString().equals(status))) && old.getMemo().equals(memo) ) { return false; } else return true; } else return false; }catch(ServiceException ex) { ex.printStackTrace(); return false; } } public String saveAssigned() { try { FaMaintain old = maintainService.findMaintainById(StringTools.parseLong(maintainId)); //判断改没有,改了就产生新日志 if(this.isModified()) { FaMaintainLog log = new FaMaintainLog(); old.setMaintainDeptId(StringTools.parseLong(maintainDeptId)); old.setMaintainUserId(StringTools.parseLong(maintainUserId)); //old.setStatus("11");//维修中 FaEquipment t = equipmentService.FindEquipmentById(old.getEquipId()); t.setMaintainDeptId(StringTools.parseLong(maintainDeptId)); t.setMaintainUserId(StringTools.parseLong(maintainUserId)); old.setStatus(status); if(status.equals("90")) { //已修复 log.setMemo(memo+"。设备已修好!"); old.setFixDate(new Date()); t.setHealthStatus("00");//正常 } else { log.setMemo(memo); } equipmentService.saveEquipment(t); old.setFixMethod(fixMethod); old.setMemo(memo); maintainService.saveMaintain(old); log.setCreateDate(new Date()); log.setMaintainId(StringTools.parseLong(maintainId)); log.setCreateDeptId(StringTools.parseLong(maintainDeptId)); log.setCreateUserId(StringTools.parseLong(maintainUserId)); maintainLogService.saveMaintainLog(log); } return SUCCESS; } catch (ServiceException ex) { ex.printStackTrace(); this.addActionError(ex.getMessage()); return INPUT; } } public String info(){ try { FaMaintain instance; instance = maintainService.findMaintainById(StringTools.parseLong(maintainId)); BeanTools.copyProperties(this, instance); this.faEquipment = equipmentService.FindEquipmentById(instance.getEquipId()); createDate = StringTools.formatDate(instance.getCreateDate()); fixDate = StringTools.formatDate(instance.getFixDate()); //找出相关日志 FaMaintainLog log = new FaMaintainLog(); log.setMaintainId(StringTools.parseLong(maintainId)); maintainLogList = maintainLogService.findMaintainLog(log, null); return SUCCESS; } catch (ServiceException e) { e.printStackTrace(); return ERROR; } } public String delete(){ String[] values = ServletActionContext.getRequest().getParameterValues("maintainId"); Long[] MaintainIds = (Long[]) ConvertUtils.convert(values, Long.class); try { maintainService.deleteMaintainById(MaintainIds); return SUCCESS; } catch (ServiceException e) { e.printStackTrace(); return ERROR; } } public String assign() { String[] values = ServletActionContext.getRequest().getParameterValues("maintainId"); Long[] maintainIds = (Long[]) ConvertUtils.convert(values, Long.class); try { for(int i = 0; i < maintainIds.length; i++) { FaMaintainLog log = new FaMaintainLog(); FaMaintain faMaintain = maintainService.findMaintainById(maintainIds[i]); log.setMaintainId(faMaintain.getMaintainId()); log.setCreateDate(new Date()); log.setCreateDeptId(faMaintain.getCreateDeptId()); log.setCreateUserId(faMaintain.getCreateUserId()); log.setMemo("下达任务"); maintainLogService.saveMaintainLog(log); faMaintain.setStatus("11"); maintainService.saveMaintain(faMaintain); } return SUCCESS; } catch(ServiceException e) { e.printStackTrace(); return ERROR; } } public FndUser getUser() { HttpSession session = ServletActionContext.getRequest().getSession(); return (FndUser)session.getAttribute(Constants.SESSION_USER); } public String execute() { try { this.faEquipment = equipmentService.FindEquipmentById(StringTools.parseLong(equipId)); return SUCCESS; } catch (ServiceException e) { e.printStackTrace(); return ERROR; } } public String getMaintainId() { return maintainId; } public void setMaintainId(String maintainId) { this.maintainId = maintainId; } public String getEquipId() { return equipId; } public void setEquipId(String equipId) { this.equipId = equipId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCreateUserId() { return createUserId; } public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } public String getCreateDeptId() { return createDeptId; } public void setCreateDeptId(String createDeptId) { this.createDeptId = createDeptId; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getReplace() { return replace; } public void setReplace(String replace) { this.replace = replace; } public String getMaintainDeptId() { return maintainDeptId; } public void setMaintainDeptId(String maintainDeptId) { this.maintainDeptId = maintainDeptId; } public String getMaintainUserId() { return maintainUserId; } public void setMaintainUserId(String maintainUserId) { this.maintainUserId = maintainUserId; } public String getFixDate() { return fixDate; } public void setFixDate(String fixDate) { this.fixDate = fixDate; } public String getFixMethod() { return fixMethod; } public void setFixMethod(String fixMethod) { this.fixMethod = fixMethod; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public FaEquipment getFaEquipment() { return faEquipment; } public void setFaEquipment(FaEquipment faEquipment) { this.faEquipment = faEquipment; } public List<FaMaintainLog> getMaintainLogList() { return maintainLogList; } public void setMaintainLogList(List<FaMaintainLog> maintainLogList) { this.maintainLogList = maintainLogList; } }
在spring的配置文件中,初始化这些bean:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><!-- Spring与Hibernate集成的桥梁 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean>
<bean id="FaMaterialDAO" class="com.ultratech.omis.fa.dao.FaMaterialDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean>
<bean id="MaintainService" class="com.ultratech.omis.fa.service.MaintainService"> <property name="maintainDAO" ref="FaMaintainDAO" /> </bean>
<bean id="MaintainEditAction" class="com.ultratech.omis.fa.web.MaintainEditAction" scope="prototype"> <constructor-arg ref="MaintainService" /> <constructor-arg ref="EquipmentService"/> <constructor-arg ref="MaintainLogService"/> </bean>
scope="prototype"(多态)是在每次用户发起请求时重新生成action对象,对于多线程访问不会出现问题,如果没有配置scope=prototype则添加的时候不会新建一个action,他任然会保留上次访问的过记录的信息。
默认是scope="singleton"(单态),这些bean被spring初始化后,始终只有一份,很适用于无状态的bean,DAO、Service都采用的这种。当然,scope的值还有session,request等等。
相关推荐
在Spring框架中,`scope`是一个非常重要的概念,它决定了Bean的生命周期和实例化策略。在Spring中,Bean的scope主要有以下几种: 1. **singleton(单例)**:这是默认的scope,每个容器中只有一个实例。无论多少次...
Spring IOC Bean标签属性介绍 0.Bean标签属性介绍 1.0 新建一个Maven工程 1.1 pom.xml 1.2 实体类JavaBean 1.2.1 User类 1.3 当Scope="singleton"时 1.4 当 Scope="singleton" 且 lazy-init="true" 时 1.5 当scope=...
<bean id="role" class="spring.chapter2.maryGame.Role" scope="prototype"/> ``` 或者 ```xml <bean id="role" class="spring.chapter2.maryGame.Role" singleton="false"/> ``` 值得注意的是,Prototype作用域...
在配置文件中,`p2`被定义为`prototype` Bean,通过`scope="prototype"`指定。在`BeanTest`中,我们请求`p2`两次并进行比较,结果发现两次得到的对象并不相同,这符合`prototype`作用域的行为。 在实际应用中,选择...
我的博客中“maven环境搭建及Spring入门”的项目代码。...* 原型 scope=“prototype” 5。bean的生命周期: 默认情况下IOC容器创建的时候就会自动创建所有对象,只支持懒加载。default-lazy-init=true
<bean id="role" class="spring.chapter2.maryGame.Role" scope="prototype"/> ``` 或者 ```xml <bean id="role" class="spring.chapter2.maryGame.Role" singleton="false"/> ``` request 作用域 -----------------...
2. **生命周期管理**:对于Singleton Bean,Spring容器会在初始化时创建实例,而对于Prototype Bean,实例化是在实际请求时进行的,这给了开发者更多的灵活性,可以根据需要控制对象的创建。 理解这两种作用域对于...
在Spring框架中,Bean的两种主要作用域是Singleton和Prototype。Singleton Bean表示在整个Spring IoC容器中只有一个实例,而Prototype Bean则表示每次请求都会创建一个新的实例。这两种作用域的使用场景和实现方式都...
<bean name="/searchEmployee" scope="prototype" class="com.mysteelsoft.action.EmployeeAction"> <property name="employeeDao" ref="employeeDao"/> </bean> <bean name="/addEmployee" scope=...
- 配置Prototype Bean的例子是:`<bean id="role" class="spring.chapter2.maryGame.Role" scope="prototype"/>` 或 `<bean id="role" class="spring.chapter2.maryGame.Role" singleton="false"/>` 3. **Request...
创建SpringBean配置工具类(安全)如: <bean id=... scope="prototype"></bean>
Spring中的singleton和prototype的实现 Spring框架中,bean的作用域是指在容器中bean的实例化和生命周期管理。其中,singleton和prototype是两个最基本的bean作用域。本文将详细介绍Spring中的singleton和...
<bean id="helloDaoImpl" class="www.csdn.spring.dao.impl.HelloDaoImpl" scope="prototype"/> ``` 在此示例中,`scope`属性的值`prototype`没有被引号包围,这违反了XML的语法规则。修正后的配置不仅遵循了XML规范...
不会新建action对象,每次调用的时候会使用原来的action,所以该类的所有字段会保留,这样异步访问的时候会出问题,所以需要将scope参数设置为prototype(多例),即在相应的action上添加属性:scope="prototype",...
然而,根据应用场景的不同,有时我们需要更灵活的管理方式,这时Spring提供了多种预定义的scope,如`prototype`、`request`、`session`、`application`和`websocket`等。 `prototype`作用域的Bean每次从容器中请求...
但是,如果需要每次请求都创建新的对象,可以将Bean的scope设置为"prototype"。这样,每次请求都会创建一个新的Bean实例。例如,在XML中: ```xml <bean id="exampleBean" class=...
这个属于与Spring整合的问题,Spring容器在初始化对象的时候会根据bean的scope配置来考虑是重新建立一个对象,还是继续使用原来的对象,拿struts2的action的bean来说,如果scope这个参数没有配置,默认就是单例,即...
Spring In Action-3.2@Scope单例、多例Bean,Spring In Action-3.2@Scope单例、多例Bean,Spring In Action-3.2@Scope单例、多例Bean,Spring In Action-3.2@Scope单例、多例Bean
<bean id="defaultPointcutAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor" scope="prototype"> <property name="pointcut" ref="fooPointcut"/> <property name="advice" ref=...
2. **原型(Prototype)**:与单例相反,`scope="prototype"`表示每次请求都会创建一个新的Bean实例。这种方式适用于有状态的Bean,比如用户会话中的模型对象。 3. **请求(Request)**:在Web应用中,如果设置`...