views:

45

answers:

1

I need to create a Spring bean so that it stores serverName, serverPort, contextPath properties of a HttpServletRequest object so that I can inject this bean to other beans as I need.

In my opinion, those properties do not change with any URI so that it is good to initialize this once (anyway, passing request instance many times is not so expensive at all).

The problem is, how can I inject HttpServletRequest instance to my configuration bean? I prefer xml based injection. Most probably we need to inject it as a <property> but I do not know what will be name or ref for this ServletRequest object.

The aim is to hold those variables in a bean so that they will be accessible from any bean and I won't need to pass request object to many methods as an argument when I need to obtain serverName etc.

Any ideas how to create such a bean and its configuration?

+2  A: 

You can do this using a request-scoped bean, and autowiring the current request into your bean:

public class RequestHolder {
   private @Autowired HttpServletRequest request;

   public String getServerName() {
      return request.getServerName();
   }
}

And then in the XML:

<bean id="requestHolder" class="com.x.RequestHolder" scope="request">
  <aop:scoped-proxy/>
</bean>

You can then wire the requestHolder bean into wheiever business logic bean you choose.

Note the <aop:scoped-proxy/> - this is the easiest way of injecting a request-scoped bean into a singleton - see Spring docs for how this works, and how to configure the aop namespace.

skaffman
Thanks a lot! Worked like magic.
Ahmet Alp Balkan