javaspringspring-properties

How to write files in different directories based on different spring-profiles?


I generate a Zip File in my code and now i want to weite it in a directory

/export

in Production then I want to write it in

/foo/bar

I already got 2 Profiles (it & Production):

application-it.yaml
application-production.yaml

But how do I manage two save locations in my code now or what propertie should I use for that?


Solution

  • In Spring Boot you can do it like this.

    'application-it.yml' content:

    file.storage: "/export"
    

    'application-production.yml' content:

    file.storage: "/foo/bar"
    

    I don't know your real implementation. But imagine that you use service to process the file. Then you can include @Value to your service to include specific variable. My 'SimpleService.java' content:

    package test.service;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    @Service
    public class SimpleService {
    
        private static final Logger LOG = LoggerFactory.getLogger(SimpleService.class);
    
        @Value("${file.storage}")
        private String fileStorage;
    
        public void saveFile() throws IOException {
            LOG.info("Folder to store files: {}", fileStorage);
    
            File file = new File(fileStorage + File.separatorChar + "test.zip");
            ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry("entry.txt");
            outputStream.putNextEntry(entry);
            outputStream.write("test".getBytes());
            outputStream.closeEntry();
            outputStream.close();
        }
    }
    

    And finally, when you start your app (in my case with Maven) specify active app profile:

    -Dspring.profiles.active=it
    

    or

    -Dspring.profiles.active=production