Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access <context-param> values of web.xml in Spring Controller

Tags:

spring

I am defining a context-param in web.xml of my application as below

<context-param>
    <param-name>baseUrl</param-name>
    <param-value>http://www.abc.com/</param-value>
</context-param>

Now i want to use the value of baseUrl in my Controller, so how i can access this.....?

Please tell me if anyone knows about this.

Thanks in advance !

like image 457
Naveen Avatar asked Nov 20 '13 10:11

Naveen


2 Answers

First, in your Spring applications "applicationContext.xml" (or whatever you named it:), add a property placeholder like this:

<context:property-placeholder local-override="true" ignore-resource-not-found="true"/>

Optional parameter of "location" could be added if you would also like to load some values found in .properties files. ( location="WEB-INF/my.properties" for example).

The important attribute to remember is the 'local-override="true"' attribute, which tells the place holder to use context parameters if it can't find anything in the loaded properties files.

Then in your constructors and setters you can do the following, using the @Value annotation and SpEL(Spring Expression Language):

@Component
public class AllMine{

    public AllMine(@Value("${stuff}") String stuff){

        //Do stuff
    }
}

This method has the added benefit of abstracting away from the ServletContext, and gives you the ability to override default context-param values with custom values in a properties file.

Hope that helps:)

like image 51
Pytry Avatar answered Oct 24 '22 20:10

Pytry


If you are using Spring 3.1+, you don't have to do anything special to obtain the property. Just use the familiar ${property.name} syntax.

For example if you have:

<context-param>
    <param-name>property.name</param-name>
    <param-value>value</param-value>
</context-param>

in web.xml or

<Parameter name="property.name" value="value" override="false"/>

in Tomcat's context.xml

then you can access it like:

@Component
public class SomeBean {

   @Value("${property.name}")
   private String someValue;
}

This works because in Spring 3.1+, the environment registered when deploying to a Servlet environment is the StandardServletEnvironment that adds all the servlet context related properties to the ever present Environment.

like image 39
geoand Avatar answered Oct 24 '22 20:10

geoand