How to access values of web.xml in Spring Controller

后端 未结 3 1456
自闭症患者
自闭症患者 2020-12-10 14:53

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


    baseUrl
    

        
相关标签:
3条回答
  • 2020-12-10 15:24

    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.

    0 讨论(0)
  • 2020-12-10 15:31

    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:)

    0 讨论(0)
  • 2020-12-10 15:34

    Make your Controller implement the ServletContextAware interface. This will force you implement a setServletContext(ServletContext servletContext) method and Spring will inject the ServletContext in it. Then just copy the ServletContext reference to a private class member.

    public class MyController implements ServletContextAware {
    
        private ServletContext servletContext;
    
        @Override
        setServletContext(ServletContext servletContext) {
            this.servletContext = servletContext;
        }
    }
    

    You can get the param-value with:

    String urlValue = servletContext.getInitParameter("baseUrl");
    
    0 讨论(0)
提交回复
热议问题