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 !
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:)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With