Accessing Application Properties in Spring-MVC

前端 未结 2 1623
情话喂你
情话喂你 2021-02-09 07:03

New to Spring-MVC.

I want to store two properties (uploadFolder=.., downloadFolder=..) in a .properties file and access it in HomeController class (automatically created

相关标签:
2条回答
  • 2021-02-09 07:26

    There are a few different ways to do it. I do the following. In app context:

    <util:properties id="myProps" location="classpath:app.properties" />
    

    Make sure you have the following at the top of your file to include the "util" namespace:

    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation= "... http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
    

    I usually put my properties files in src/main/resources. As long as they're on the classpath, you're good. Then, in your controller, you can annotate your field/method with:

    @Controller
    public class MyController {
    
        @Value("#{myProps['uploadFolder']}")
        private String uploadFolder
    
        @Value("#{myProps['downloadFolder']}")
        private String downloadFolder
    
        @RequestMapping("myPage")
        public String loadPage(ModelMap m) {
            m.addAttribute("uploadFolder", uploadFolder);
            m.addAttribute("downloadFolder", downloadFolder);
            return "myPage";
        }
    
        public void setUploadFolder(String uploadFolder) {
            this.uploadFolder = uploadFolder;
        }
        public void setDownloadFolder(String downloadFolder) {
            this.downloadFolder = downloadFolder;
        }
    }
    

    Then, in your JSP:

    Download folder: ${downloadFolder} <br/>
    Upload folder: ${uploadFolder}
    

    HTH. Let me know if you have any questions.

    0 讨论(0)
  • 2021-02-09 07:30

    1) Better way is by using src/main/resources

    2) yes, but this messageshave different purpose

    3)

    One way to make a bean from the properties file in src/main/resources:

    <bean id="foldersConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
       <property name="location" >
          <value>/WEB-INF/classes/folders.properties</value>
       </property>
    </bean>
    

    And in your controller simply inject the reference.

    Here how your controller will look like, the xml:

    <bean id="myController" class="my.project.package.controller.MyController">
     ...
     <property name="foldersConfig" ref="foldersConfig" />
    </bean>
    

    The controller class, related part:

    public class MyController extends ... {
    
     private Properties foldersConfig;
    
     public void setFoldersConfig(Properties config) {
       this.foldersConfig = config;
     }
    }
    

    4) You can access if you put the properties in the View - Model, but this not good solution. Take what you need in the controller (the paths) and put it in the result.

    0 讨论(0)
提交回复
热议问题