在Java Jersey RESTful Web应用程序中加载属性文件,以在整个应用程序中保留? [英] Loading properties file in a Java Jersey RESTful web app, to persist throughout the app?
问题描述
我目前正在使用Jersey构建RESTful API。到目前为止,一切进展顺利,但是,所有配置条目都已经过硬编码。(即数据库主机,数据库用户名等...)。
I'm currently building a RESTful API using Jersey. So far, all has been going well, however, all of the configuration entries have been hard coded in. (i.e. Database Host, Database Username, etc...).
我希望能够设置我的<$ c $中存在的 config.properties
文件c> WEB-INF 包含所有这些配置规范的文件夹。
I'd like to be able to setup a config.properties
file that exists in my WEB-INF
folder to contain all of these configuration specs.
我担心如果我在Classpath上读取文件的经典方式,我就会为每个请求执行文件I / O.我希望能够在启动时读取一次(我知道在我的 web.xml
文件中涉及 ServletListener
。
I'm concerned that if I do it the "classic" way of reading the file on the Classpath, I'm performing file I/O for every request. I want to be able to read once on startup (which I know involves a ServletListener
in my web.xml
file.
以下是我的内容:
web.xml :
<listener>
<listener-class>com._1834Software.Config</listener-class>
</listener>
我想做这样的事情(我发现这里 StackOverflow)但我不认为与泽西岛一起工作:
I'd like to do something like this (which I found here on StackOverflow) but I don't think it works necessarily with Jersey:
Config.java
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();
@Override
public void contextInitialized(ServletContextEvent event) {
try {
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
} catch (IOException err) {
err.printStackTrace();
}
event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}
@Override
public void contextDestroyed(ServletContextEvent event) { /**/ }
public static Config getInstance(ServletContext context) {
return (Config) context.getAttribute(ATTRIBUTE_NAME);
}
public String getProperty(String key) {
return config.getProperty(key);
}
}
我试着这样称呼它:
Config config = Config.getInstance(getServletContext());
String property = config.getProperty("HEROKU_DATABASE_URL");
但我收到以下错误:
Error:(32, 40) java: cannot find symbol
symbol: method getServletContext()
location: class com._1834Software.database.DatabaseHandler
这是文件( DatabaseHandler.java
我在哪里我试图调用它):
And here is the file (DatabaseHandler.java
where I'm trying to call it):
public class DatabaseHandler {
public Connection connection = null;
Config config = Config.getInstance(getServletContext());
String property = config.getProperty("somekey");
/* Database Parameters */
private String DRIVER = "org.postgresql.Driver";
private String host = "XXXXX";
private String userName = "XXXXX";
private String password = "XXXXX";
public void connect() throws SQLException {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException err) {
err.printStackTrace();
}
try {
connection = DriverManager.getConnection(host, userName, password);
} catch (SQLException err) {
err.printStackTrace();
}
}
public void disconnect() throws SQLException { connection.close(); }
}
推荐答案
有很多方法可以加载属性文件。为避免在您的项目中引入任何新的依赖项,以下是一些可能对您有帮助的代码段。这只是一种方法...
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...
-
定义属性文件。我把它放在src / main / resources /中作为config.properties
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");
}
}
这篇关于在Java Jersey RESTful Web应用程序中加载属性文件,以在整个应用程序中保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!