Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » Struts 2 »

How to use IoC in struts2?

Peder Larsen

2006-12-21

Replies:

Hi, i've got one very basic question that i cant find any documentation for
nor any examples, maybe i've missed it but..

What i want to is to inject a UserInfo object into my action. In webwork2
you used components.xml for this. E.g,
  <component>
    <scope>session</scope>
    <class>foo.acme.UserInfo</class>
    <enabler>foo.acme.UserInfoAware</enabler>
  </component>

to tell the IoC framework (is it xwork?) to inject the UserInfo into any
Action implementing UserInfoAware.

Now, I've managed to inject it in struts2 as well, but i cant find a way to
inject ONE UserInfo pr session, i can only specify singleton="true" or
"false" in "applicationContext.xml".

I paste my struts.xml and applicationContext.xml here so a more enlightened
soul may give me some clue,
struts.xml,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="unrestrictedActions" extends="struts-default" >
    <interceptors>
      <interceptor name="login" class="
foo.acme.interceptor.LoginInterceptor"/>
      <interceptor-stack name="secureStack">
       <interceptor-ref name="login"/>
       <interceptor-ref name="defaultStack"/>
      </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="secureStack"/>

    <action name="index" class="indexAction">
       <result type="freemarker">/ftl/index.ftl</result>
    </action>
  </package>
</struts>
applicationContext.xml,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
  "-//SPRING//DTD BEAN//EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="userInfo" class="foo.acme.UserInfo" singleton="false"></bean>

  <bean id="indexAction" class="foo.acme.actions.IndexAction"
singleton="false">
    <property name="userInfo"><!-- THIS INJECTS THE USERINFO BUT IT
INJECTS A NEW EVERY REQUEST, WANT 1 PR SESSION -->
       <ref local="userInfo" />
    </property>
  </bean>
</beans>

Maybe theres an altogether better way of setting up the IoC in struts2? Im
all ears.

Best regards, Peder Jensen.
©2008 junlu.com - Jax Systems, LLC, U.S.A.