Loading properties file in a Java Jersey RESTful web app, to persist throughout the app?

自古美人都是妖i 提交于 2019-12-05 17:50:16

There are many ways to load properties files. To avoid introducing any new dependencies on your project, here are some code snippets that may help you. This is just one approach...

  1. Define your properties file. I put mine in src/main/resources/ as "config.properties"

    sample.property=i am a sample property
    
  2. In your jersey config file (assuming you are using class extending Application), you can load the properties file there and it will only be loaded once during the application initialization to avoid your concern of doing the File I/O over and over:

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashSet;
    import java.util.Properties;
    import java.util.Set;
    
    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    
    @ApplicationPath("sample")
    public class JerseyConfig extends Application {
    
    public static final String PROPERTIES_FILE = "config.properties";
    public static Properties properties = new Properties();
    
    private Properties readProperties() {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
        if (inputStream != null) {
            try {
                properties.load(inputStream);
            } catch (IOException e) {
                // TODO Add your custom fail-over code here
                e.printStackTrace();
            }
        }
        return properties;
    }
    
    @Override
    public Set<Class<?>> getClasses() {     
        // Read the properties file
        readProperties();
    
        // Set up your Jersey resources
        Set<Class<?>> rootResources = new HashSet<Class<?>>();
        rootResources.add(JerseySample.class);
        return rootResources;
    }
    
    }
    
  3. Then you can reference your properties in your endpoints like this:

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("/")
    public class JerseySample {
    
        @GET
        @Path("hello")
        @Produces(MediaType.TEXT_PLAIN)
        public String get() {
            return "Property value is: " + JerseyConfig.properties.getProperty("sample.property");
        }
    
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!