我正在使用 Java、Tomcat 和 Jersey 创建一个 REST Web 应用程序。我正在使用注释(没有 web.xml!)我最终使用了这个应用程序配置:
package com.my_own.server;
import java.util.Properties;
import javax.ws.rs.ApplicationPath;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.my_own.db.PostgreSQLDb;
@ApplicationPath("/api")
public class Application extends javax.ws.rs.core.Application {
private static Logger logger = LogManager.getLogger(Application.class);
public static Application application = null;
public final Properties properties;
public final PostgreSQLDb adminDb;
public Application() throws Exception {
logger.debug("Loading properties from ",
getClass().getClassLoader().getResource("config.properties"));
properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
adminDb = new PostgreSQLDb(properties, "admin");
application = this; // Setting the global application object here
}
}
这是我的问题。 Web 容器有一个全局应用程序对象。我将其从应用程序构造函数保存到静态字段中。稍后我需要从其他类访问它(它保存全局配置、全局数据库连接工厂,可能还有其他东西。)
我这样做对吗?我怀疑一定有更好的方法:在处理注释时保存对应用程序的引用。但我不知道怎么做。我能否确定应用程序的构造函数将被调用一次,并且以后可以通过任何 REST 调用访问 Application.application 引用?
最佳答案
在 jersey 中使用依赖注入(inject),初始化时绑定(bind)您的应用程序:
public class MyApplication extends ResourceConfig {
public MyApplication() {
super(MyApplication.class);
register(new MyBinder());
packages(true, "location.of.my.jersey.classes");
}
/* Bind is used to let jersey know what can be injected */
private static class MyBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MyApplication.class).to(MyApplication.class);
}
}
}
然后在您的代码中:
@Path("myapi")
@Produces(MediaType.APPLICATION_JSON)
public class ServerRoutes {
@Inject
MyApplication application;
//... your rest code here
}
现在您可以从代码中访问 MyApplication,而无需任何静态或单例,jersey 可以处理它。
关于java - Jersey:如何访问全局应用程序对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47846657/