How to use Spring ServletContextAttributeExporter

Vishu Guntupalli
Intelicloud
Published in
2 min readMar 14, 2015

Very recently I ran into a situation where I had a context parameter with a property placeholder defined in my web.xml and maven was resolving the property at build time for me but I had to make the properties more dynamic and make Spring resolve them for us in runtime according to the environment being deployed to.

Snip20150314_6

As shown above, the property was in web.xml and it was being resolved by maven at build time. The property was being accessed in java code the following way

String url = getServletContext().getInitParameter(“cas.server.login”);

I had to make the property resolvable by spring at runtime (i.e read from the appropriate property file depending on the environment and replace the property placeholder) but the java code must still be able to read the property from the servlet context. So I made use of ServletContextAttributeExporter class provided by Spring and injected the property into the ServletContext the following way

Snip20150314_9

What Spring does for you is resolve the property placeholder at runtime and inject that value into the Servlet context.

You can still access this property in java through servlet context like this

String url= getServletContext().getAttribute(“cas.server.url”);

You have to retrieve the property through getAttribute method instead of getInitParameter. Hope this post explains what ServletContextAttributeExporter is, please leave a comment if you have any questions.

--

--

Vishu Guntupalli
Intelicloud

Software engineer/architect, Entrepreneur, AWS, Python, Data, Cloud