我目前正在使用 Jersey 构建 RESTful API。到目前为止,一切进展顺利,但是,所有配置条目都已硬编码。(即数据库主机、数据库用户名等...)。
我希望能够设置一个存在于我的 WEB-INF 文件夹中的 config.properties 文件,以包含所有这些配置规范。
我担心如果我以“经典”方式读取类路径上的文件,我会为每个请求执行文件 I/O。我希望能够在启动时读取一次(我知道这涉及到我的 web.xml 文件中的 ServletListener。
下面是我的内容:
web.xml:
<listener>
<listener-class>com._1834Software.Config</listener-class>
</listener>
我想做这样的事情(我在 StackOverflow 上找到了 here),但我认为它不一定适用于 Jersey:
配置.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,我正在尝试调用它):
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(); }
}
最佳答案
加载属性文件的方式有很多种。为避免在您的项目中引入任何新的依赖项,以下是一些可能对您有所帮助的代码片段。这只是一种方法...
定义您的属性文件。我把我的放在 src/main/resources/作为“config.properties”
sample.property=i am a sample property
在你的 jersey 配置文件中(假设你正在使用扩展应用程序的类),你可以在那里加载属性文件,它只会在应用程序初始化期间加载一次,以避免你担心文件 I/O一遍又一遍:
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;
}
}
然后您可以像这样在端点中引用您的属性:
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 - 在 Java Jersey RESTful Web 应用程序中加载属性文件,以在整个应用程序中持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29543597/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序