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.