Can I use an Environment variable based location for Spring FileSystemResource?

前端 未结 5 600
清歌不尽
清歌不尽 2020-12-01 05:45

I have a requirement to have all our properties files be stored in a directory. The location of this directory should be stored in a system environment variable. In my appli

5条回答
  •  执笔经年
    2020-12-01 06:34

    Example:

    Start you app with -DDA_HOME=c:\temp

    c:\temp must contain directory called "config"

    In c:\temp\config you have file app.properties (for example)

    Extend the Spring loader:

    public class Loader extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer{
    
        private String appHome;
    
        public void setAppHome(String appHome) {
            this.appHome = appHome;
        }
    
        @Override
        public void setLocation(Resource location) {
            if(appHome==null){
                throw new RuntimeException("You must specify VM property DA_HOME, this directory must contain " +
                        "another directory, called config, inside the config directory app.properties " +
                        "file must be found with the configuration properties");
            }
            String configurationDirectory = appHome + System.getProperty("file.separator") + "config";
            String fileName = location.getFilename();
            Resource file = new FileSystemResource( configurationDirectory + System.getProperty("file.separator")+ fileName);
            super.setLocation(file);
        }
    }
    

    Specify the new loader and its configuration base:

        
            
            
        
    

提交回复
热议问题