繁体   English   中英

Jersey RESTful:Spring bean创建管理

[英]Jersey RESTful: Spring bean creation management

我有以下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实例, 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.dbControllerAnotherService.dbController引用同一个对象?

如果我想在非Jersey类(例如,服务层类)中使用第一个DAO对象CustomerService.dbController ,我是否应该使用第一种方法仅在一个Jersey类中创建bean作为公共静态变量并将其引用到所有使用dbController类? 这里的最佳做法是什么?

最佳实践是使用@Inject而不是static 泽西有自己的注射机制

public class MyApplication extends ResourceConfig {
public MyApplication() {
    register(new FacadeBinder());

注册为Singleton

public class FacadeBinder extends AbstractBinder {

  @Override
  protected void configure() {
    bind(MyManager.class).to(MyManager.class);
  }
}

然后在资源端点中,您可以使用已注册的类:

@Path("/jersey")
public class MyEndpoint implements MyInterface {
  @Inject
  MyManager myManager;

或者您可以与其他一些注入框架集成,例如Guice或Spring。

首先,如果你计划使用Jersey + Spring,我认为jersey-spring集成值得一试

此外,使用任何依赖注入/控制反转框架的重点是管理“bean”的生命周期和相互依赖性。 DI / IoC库和框架在这里避免了这种静态/依赖性的恶梦,并帮助您构建可测试的,可扩展的应用程序。

Spring参考文档的这一部分应该让事情变得更加清晰。 默认情况下 ,Spring为您创建和管理单例bean(一个实例在您的应用程序中共享)。 查看beans scopes文档

一般经验法则:直接注入/使用应用程序上下文有点代码味道(特别是如果你硬编码上下文文件的名称!)。

如果您正在寻找最佳实践, Jersey + Spring示例应该可以帮助您

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM