jax-rs (rest api)和websockets的组合-在哪里放置公共初始化



我正在开发一个涉及JAX-RS(用于REST API)和Websocket(用于通知)的项目。该项目将作为WAR部署到应用服务器中。

对于JAX-RS,我做了以下操作:

@ApplicationPath("/")
public class MyApplicationREST extends ResourceConfig {
    public MyApplicationREST() {
        ... initialization here ...
    }
}

对于Websockets,我做以下操作:

public class MyApplicationWebsockets implements ServerApplicationConfig {
    ... callbacks for discovery of endpoints here ...
}

当部署WAR时,这两个类都被应用服务器(在我的例子中是Tomcat)完美地拾取,并在真空中正常工作。

然而,在这两个类中,我都需要一个对命令实例的引用(在本例中是数据库连接,但它可以是任何东西)。我不能在上面两个类中的一个中实例化它(并在另一个类中使用它),因为不能保证这两个类的初始化顺序。

最好的方法是什么?

初始化

(1)创建一个类实现ServletContextListener

(2)在contextInitialized(ServletContextEvent)方法中编写初始化代码。

public class MyContextListener implements ServletContextListener
{
    @Override
    public void contextInitialized(ServletContextEvent context)
    {
        // Your initialization code here.
    }

    @Override
    public void contextDestroyed(ServletContextEvent context)
    {
        // Your finalization code here.
    }
}

(3)将类注册为web.xml中的侦听器。

<listener>
    <listener-class>com.example.MyContextListener</listener-class>
</listener>


共享实例

对于共享实例,单例模式是实现它的可能手段之一。

public class DB
{
    private static final DB sInstance = new DB();
    // Private constructor to prevent DB instances from being created by others.
    private DB()
    {
    }
    // Get the singleton instance.
    public static DB getInstance()
    {
        return sInstance;
    }
}

最新更新