0

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
ahmet alp balkan
  • 42,679
  • 38
  • 138
  • 214
  • 3
    I think this is a bad idea. Why should layers outside of the web tier need to know these things? Feels like you're letting web information leak into the rest of your app. – duffymo Aug 18 '10 at 18:02

1 Answers1

4

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
  • 398,947
  • 96
  • 818
  • 769