SSH——单例模式引起的服务器启动错误

来源:互联网 发布:npm 换淘宝源 编辑:程序博客网 时间:2024/05/21 07:58

这个错误困扰了我一个星期,当我写入第一个bean(userBean)的时候,可以正常使用,用户可正常注册登录,当写入第二个bean的时候,出现了如下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serviceActionBean’ defined in

ServletContext resource [/WEB-INF/bean.xml]: Cannot resolve reference to bean ‘serviceDao’ while setting bean property

‘serviceDao’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name

‘serviceDao’ defined in ServletContext resource [/WEB-INF/bean.xml]: Error setting property values; nested exception is

org.springframework.beans.NotWritablePropertyException: Invalid property ‘sessionFactory’ of bean class

[com.swu.dao.impl.ServiceDao]: Bean property ‘sessionFactory’ is not writable or has an invalid setter method. Does the

parameter type of the setter match the return type of the getter?

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serviceDao’ defined in

ServletContext resource [/WEB-INF/bean.xml]: Error setting property values; nested exception is

org.springframework.beans.NotWritablePropertyException: Invalid property ‘sessionFactory’ of bean class

[com.swu.dao.impl.ServiceDao]: Bean property ‘sessionFactory’ is not writable or has an invalid setter method. Does the

parameter type of the setter match the return type of the getter?
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property ‘sessionFactory’ of bean class

[com.swu.dao.impl.ServiceDao]: Bean property ‘sessionFactory’ is not writable or has an invalid setter method. Does the

parameter type of the setter match the return type of the getter?

错误信息是bean注入失败,无效的sessionFactory,然后我仔细检查代码,没找到错误,重写了java代码还是报错,将此项目拷到其他人电脑中,可正常运行,一开始我以为是我自己的环境问题,重装了Java、tomcat等都不行,经过询问老师、同学与网友,终于将错误找了出来。
原代码 :










其实以前都是这样写的,并没有错误, 而这次错误也提醒了我对线程安全的关注。

在Spring的bean配置中,如果不声明,都是默认的单例模式, 而所创建的sessionFactory因为是单例的,所以会被重复使用,当多线程访问时,多个请求对同一bean进行使用,会导致各种异常,称为不安全线程。tomcat服务器禁止了对不安全线程sessionFactory的读写。

解决方法:

struts+spring action应配置为scope=”prototype”



在配置文件中,bean默认是单例模式,应用服务器启动后就会立即创建bean,以后就可以重复使用。
这带来一个问题,bean的全局变量被赋值以后,在下一次使用时会把值带过去。也就是说,bean是有状态的。在web状态下,请求是多线程的,全局变量可能会被不同的线程修改,尤其在并发时会带来意想不到的bug。而在开发时,访问量很小,不存在并发、多线程的问题,程序员极有可能会忽视这个问题。所以在配置action bean时,应使用scope=”prototype”,为每一次request创建一个新的action实例。这符合struts2的要求,struts2为每一个request创建一个新的action实例。当request结束,bean就会被jvm
销毁,作为垃圾收回。当然,也可以设置scope=”session”,也能避免web中action的并发问题,只为当前用户创建一次bean,直至
session消失。在这种情况下,对当前用户而言,bean是有状态的。好处就是少创建bean的实例,有那么一
点点性能的提升应用场景:
1. 多数情况下应使用prototype
2. 若用户不多,且频繁操作(频繁使用action),硬件一般,可以考虑session,兴许还能提升一点点性能。

0 0
原创粉丝点击