struts2+spring中action的生命周期问题

来源:互联网 发布:iphone软件更新小红点 编辑:程序博客网 时间:2024/05/16 02:38

将struts2中的action交给spring管理

如果没有指定scope就会出现验证时第一次验证的结果一直存在,导致后面的验证根本没有进行

所以在spring中配置action时要指定scope属性为prototype

<bean id="randomImageAction"
class="cn.link.sgums.action.RandomImageAction" scope="prototype">
这样就ok了

默认的spring的bean的周期是单态的(Singleton)

对于每一次请求不会生成新的实例

Spring里默认情况下,用BeanFactory和ApplicationContext获得的bean实例都是一个。看下面这个例子:

public class HelloBean2 {     private String name;     private String helloWord;     public String getName() {        return name;     }     public void setName(String name) {       this.name = name;     }     public String getHelloWord() {     return helloWord;     }     public void setHelloWord(String helloWord) {        this.helloWord = helloWord;     } } 


Bean的定义:

 <bean id="helloBean"   class="onlyfun.caterpillar.HelloBean2" singleton="true">    <property name="helloWord" value="test"/>    <property name="name" value="Tom"/>     </bean>


测试:

ApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml"); HelloBean2 helloBean1 = (HelloBean2)context.getBean("helloBean"); helloBean1.setName("jack"); System.out.println(helloBean1.getName()); HelloBean2 helloBean2 = (HelloBean2)context.getBean("helloBean"); System.out.println(helloBean2.getName()); 


输出结果为: jack jack
由此可以看出在Spring容器中,默认情况下,每一个bean只有一个实例。
我们对bean的配置文件做一些修改: 加上了singleton="false" 这个配置,再执行上面的测试,结果为: jack Tom 这时每次去获得helloBean的实例,就是一个新的实例了。(singleton默认是等于true)。
对于Spring2.0,上面的配置可以改成:scope = "prototype" , scope的默认预设值singleton,针对Web应用,scope的值还可以设置为“request”,"session","globalSession"分别对应web的请求阶段,会话阶段,web应用程序阶段。

原创粉丝点击