且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java Jersey RESTful Web应用程序中加载属性文件,以在整个应用程序中保留?

更新时间:2021-11-22 04:19:11

有很多方法可以加载属性文件。为避免在您的项目中引入任何新的依赖项,以下是一些可能对您有帮助的代码段。这只是一种方法...

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. 定义属性文件。我把它放在src / main / resources /中作为config.properties

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

sample.property=i am a sample property


  • 在您的泽西配置文件中(假设您正在使用类扩展应用程序),您可以加载属性文件在那里,它只会在应用程序初始化期间加载一次,以避免您一遍又一遍地执行文件I / O:

  • 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;
    }
    
    }
    


  • 然后你可以参考您的端点中的属性如下所示:

  • 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");
        }
    
    }