Eleeist
Eleeist

Reputation: 7041

Inject HttpServletRequest (from Struts2 action implementing ServletRequestAware) into property using Spring

I am using Struts2 with Spring for dependency injections.

I have Struts action A from which I can access HttpServletRequest and some dependency B inside it:

public class A extends ActionSupport implements ServletRequestAware {
    private B b;
    private HttpServletRequest request;

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest)
    {
        this.httpServletRequest = httpServletRequest;
    }

    public B getB() {
        return this.b;
    }

    public void setB(B b) {
        this.b = b;
    }
}

There is also application-context.xml:

<bean id="b" class="com.example.B" />
<bean id="a" class="com.example.actions.A">
    <property name="b" ref="b" />
</bean>

The program works, but here is my problem: dependency B requires HttpServletRequest to function properly. Is there a way for Spring to inject it in B? Right now I would need to pass HttpServletRequest object manually to methods that require it.

Upvotes: 0

Views: 264

Answers (1)

Roman C
Roman C

Reputation: 1

Is there a way for Spring to inject it in B?

Yes, but B should be request scoped.

You pass the request object that you have got from Struts, but your actions are managed by Spring, and you want to use Spring DI to inject HttpServletRequest object? You can inject only object that is bound to thread via RequestAttributes.

You can inject this object only if it's available to Spring. You can get request object any other way but injection works only to the corresponding scope.

Upvotes: 1

Related Questions