【发布时间】:2013-11-27 20:26:15
【问题描述】:
我有以下 Jersey RESTful Web 服务类来服务 HTTP 请求/响应:
@Path("/customer")
public class CustomerService {
private static ApplicationContext context;
public static CustomerJDBCTemplate dbController;
static {
context = new ClassPathXmlApplicationContext("beans.xml");
dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
}
//methods for GET/POST requests ...
}
这里我使用静态变量dbController 作为我的DAO 对象。因为我希望在我的应用程序中只有一个dbController 实例,所以我给它一个静态属性,以便所有Jersey 类可以共享相同的dbController 实例。例如,如果我有另一个使用 DAO 的 Jersey 类,那么我可以将它用作 CustomerService.dbController.create() 之类的东西。但我想知道这是否是在 Jersey 类中实例化 DAO bean 的正确和最合适的方法,因为如果未调用 Path: /customer 处的资源,则不会实例化 DAO bean。
我也可以在另一个 Jersey 类中重复上述 bean 实例化步骤:
@Path("/another")
public class AnotherService {
private static ApplicationContext context;
public static CustomerJDBCTemplate dbController;
static {
context = new ClassPathXmlApplicationContext("beans.xml");
dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
}
//methods for GET/POST requests ...
}
我的问题是:这会创建与第一个不同的实例吗?还是CustomerService.dbController 和AnotherService.dbController 指的是同一个对象?
如果我想在非 Jersey 类(例如,服务层类)中使用第一个 DAO 对象 CustomerService.dbController,我是否应该使用第一种方法仅在一个 Jersey 类中创建 bean 作为公共静态变量和在所有使用dbController 的类中引用它?这里的最佳做法是什么?
【问题讨论】:
标签: java spring rest dependency-injection jersey