3

When I previously developed servlet applications without Spring, I could read configuration parameters like this in my servlet:

@Override public void init() throws ServletException { 

    ServletContext sc = getServletContext();
    String someSetting = sc.getInitParameter("someSetting");

}

However, I'm developing an application with Spring MVC now, which means I no longer have a servlet myself, but use Spring's DispatcherServlet.

Now, how can I access those init parameters in spring-servlet.xml to pass them to one of my beans?

I'm using Spring 3, and am a n00b with it. Every time I see a bean without an id, my mind flips XD

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301

2 Answers2

3

I guess you can @Inject a ServletContext in your controllers, and take the params from there.

Of better, use @Value together with a specificPropertyPlaceholderConfigurer. See this answer

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Do you really need these to be init-parameters in the Servlet context?

In Spring you can just inject values into your beans from a properties file using PropertyPlaceholderConfigurer.

matt b
  • 138,234
  • 66
  • 282
  • 345
  • 1
    Yes, they should come from the servlet context because that's the only place to inject local configuration data without putting it inside the webapp. Even if I put all configuration in a properties file, I'd need to insert the location of that file with an init-parameter, which I can specify in Tomcat's context file for this app. – Bart van Heukelom Apr 29 '11 at 09:57
  • a PropertyPlaceholderConfigurer is configured in your Spring context files, with a path to a file that is usually loaded from the classpath. You then inject values into other beans with references like ``. – matt b Apr 29 '11 at 13:17
  • 1
    Yes I know, but I can't put configuration in the classpath, because that means putting it inside the webapp's root directory, which should be a black box to the deployer (and also brings pain when you have multiple instance of the app, such as for testing and live). – Bart van Heukelom Apr 29 '11 at 17:47
  • loading from the classpath is merely one option, you could also load from any absolute path in the filesystem. Regardless, the advantage of using propertyPlaceholders are merely injecting values into your Spring beans is that the classes can remain ignorant of the Servlet environment - the same class can be re-used a-okay in non-webapps. – matt b Apr 29 '11 at 19:00
  • 1
    An absolute path isn't much better, so the path must be passed in from the outside. Init params are perfect for that. I do agree about the advantage of injecting though, which is why I've wrapped the servlet context in a `Config` class. – Bart van Heukelom Apr 29 '11 at 20:26