How to access values of web.xml in Spring Controller

后端 未结 3 1457
自闭症患者
自闭症患者 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:31

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

    
    

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

提交回复
热议问题