Spring autowiring Struts 1 Actions

That’s right. Struts 1. Not hip. Not happenin’. But in the real world you might have bills to pay and a pair-programmer to feed.

The docs are a bit sketchy with Spring 2.5 stuff.

First you set up your service layer in web.xml

Inside my spring-service-layer.xml file I tell spring to look for classes annotated with one of the 2.5 @Component stereotypes – which include the @Service annotation.

Here’s a simple service:

Spring will create a root web context in application scope accessible with the attribute name org.springframework.web.context.WebApplicationContext.ROOT. My service appears here.

The Spring docs say one approach is to configure Spring to manage your Actions as beans, using the ContextLoaderPlugin which will read the appropriately specified spring config files like this:

Then in action-servlet.xml for example you configure your actions as beans.

Then in struts-config.xml you specify a special Spring controller:

Also in struts-config.xml you have to change your actions definitions to use a Spring delegate. Notice
that the path matches the bean name specified in action-servlet.xml.

Ok, that works fine. Not too dry though since I have to specify the bean twice.

Let’s try a newer Spring class.

In struts-config.xml I change the controller to this.

Since it’s named AutowiringRequestProcessor I’ve used the @Autowire annotation in my Action to get the service injected (which will NOT work if you annotate the instance variable and not a setter method).

The docs say that you specify just the usual action tag in struts-config.xml.
But how will the action beans then be created?
I simply annotated HelloAction with @Component. The scan for the service found the action too. The thing is, they live in the parent web context not in the child context created by the contextLoader plugin:

The beans you specify in your plugin config file live here. But since we’re doing the component scan chacha they aren’t living there anymore. Do you think that’s a bad thing?

Here’s my annotated Action:

Here is a mavenized project with all the sources for this post.

3 thoughts on “Spring autowiring Struts 1 Actions”

  1. Hello Gene,

    Great photo of you and your “pair programmer”! I have three of my own. And you’re right, there’s nothing sexy about Struts 1, but the reality is that some of us still make a living with these outdated technologies.

    Keep blogging!

    Tina

  2. Thanks, Gene, very helpful! Exactly what I was looking for.
    A special thank-you for the test setup in the sample project download! That was my next step, and it was a pleasant surprise to find tests in the sample.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.