Using Struts 2’s native dependency injection support

Since I knew that Struts 2 used Guice internally, I was curious if the native DI support in S2 could be used in a simple application. A little bit of digging and fiddling around showed what is possible.

struts.xml

...
 <constant name="myVal" value="9" />
 <bean name="myService" type="prac.MyService" class="prac.MyServiceImpl" />
...

MyServiceImpl.java

...
 @Inject("myVal")
 public void setMyVal(String myVal) {
 this.myVal = Integer.parseInt(myVal);
 }
...

MyAction.java

...
 @Inject("myService")
 public void setMyService(MyService myService) {
 this.myService = myService;
 }
...

This will create a single instance of MyService with myVal injected into it.
And on every invocation of MyAction, that MyService instance will be injected into it.
Sweet!

Of course, this is part of Struts internals, so these can change at any time. It is probably not a good idea to use it on a real world system.

4 comments

  1. kindly send me a hello world type example of native dependecy injection in struts2 actually i tried above but having no mapping found for dependency exception
    thx
    Regards,

    ****************************
    Muhammad Ali Khan
    Associate Software Engineer
    i2c inc. Lahore, Pakistan
    92-42-111000911, ext. 155
    Mobile: +92 3214335049
    http://www.i2cinc.com
    ****************************

  2. Native S2 DI is facilitated by XWork which is part of S2 core. It is solid and works nicely in production. For what it’s worth Bob Lee (the author of Guice) wrote this too! Enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *


four + = 13

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>