Service Locator Pattern


EJB design: Service Locator Pattern

  1. Service Locator Pattern (3 messages)


    I am trying to reuse my getConnection() method for getting Connection. Here is a code snippet -

    private Connection getConnection() throws Exception {
            DataSource dsource = null;
            Context ctx = null;
            try {
                Hashtable parms = new Hashtable();

               ctx = new InitialContext(parms);
                dsource = (DataSource) ctx1.lookup(..<
            } catch (NamingException e) {
            } catch (Exception ex) {
                throw ex;
            } finally {
                try {


                } catch (Exception e) {



    But I am repeating this code everywhere i need the conncetion. I know about "Service Locator" pattern, but I don't have any EJB's, so my question is -

    How can i use the above code with "Service Locator" pattern. My whole objective is not to make 10 calls for the same stuff and make the code robut.

    May be J2EE Designers can find this question relatively easy. Also, I will greatly appreciate if you reply back with code snippet..

    Thanks a lot

    Threaded Messages (3)

  2. Service Locator Pattern[ Go to top ]

    The usage of design patterns is not restricted to EJB or J2EE. You can have your class read the config info from a property or XML file. You can use a singleton class with private contructor to initialize the Datasource lookup once, every subsequent call to get Connection will not require JNDI lookup. I am showing the simplest implementation. You can add a separate factory class.

    //To use this class
    Connection con= DBConnectionService.getInstance().getConnection();

    public class DBConnectionService {

    private DataSource ds=null;
    private static DBConnectionService myInstance;
    public static DBConnectionService getInstance(Properties prop) throws Exception {
        if (myInstance == null)
            myInstance = new DBConnectionService(prop);
        return myInstance;

    private DBConnectionService(Properties prop) throws Exception {
        //Do your lookup here ....
        ds = ......

    public Connection getConnection() { return ds.getConnection();}

  3. Service Locator Pattern[ Go to top ]


    The most made usage of service locator is not for getting the connection but for different lookups like the JNDI name etc, where we store the connection details or the look up of a ejb in a hashmap/hashtable.

    You may need to implement the DAO pattern for this which works like this. I will attach a small snippet of code for this and then make a final judgement

    Also see the method that I have written incase you dont get the connection from the context hence creating a new connection object. This is very important.


    private transient DataSource dataSource = null;
    private transient DataSource dataSource_temp = null;
    private transient Connection objConn = null;

    The constructor that does the lookup to this.
    JNDINames.SERVERSIDE_DATASOURCE has the address of database (the URL)
            * Constructor that throws a System exception incase it is not
            * able to get hold of the JNDI Name during lookup
            * @throws ServerSideException
    public ServerSideDAO() throws ServerSideException {
            try {
                InitialContext ic = new InitialContext();
                dataSource = (DataSource)
    } catch (NamingException ne) {
                throw new ServerSideException (
                        "NamingException while looking" +
                        " up DataSource Connection "
                        + JNDINames.SERVERSIDE_DATASOURCE
                        + ": \n" + ne.getMessage());

         * This method is to get a new connection
         * @return Connection object
    * @throws Exception
    private Connection getConnection () throws Exception {

            try {
                if (null != dataSource) {
    objConn = dataSource.getConnection ();
    } catch (SQLException sqle) {
    return objConn;

         * This method is to get a connection from the context. If it does
         * not exist in the context, we create a new connection
         * @param Context
         * @return Connection object
         * @throws ClaimException
    private Connection getConnectionFromCtx (Context _ctx)
    throws ServerSideException {
    Object _dsObj = null;
    if (null != _ctx) {
    try {
    _dsObj = _ctx.lookup(JNDINames.SERVERSIDE_LOOKUP);
    if (null == dataSource_temp) {
    if (null != _dsObj && _dsObj instanceof DataSource) {
    dataSource_temp = (DataSource) _dsObj;
    if (null != dataSource_temp) {
    objConn = dataSource_temp.getConnection();
    } catch (NamingException ne){
    } catch (SQLException se){
    return objConn;


            protected void finalize () throws Throwable {
    //dataSource = null;
    dataSource_temp = null;

    Hope this solves the problem for you, Incase you have any doubts please mail me back I will be more than helpful to reply back.


  4. Service Locator Pattern[ Go to top ]

    Your previous reply was so accurate, I thought of asking 2 more questions.

    The questions are related to the architectural issues

    1. I am calling a Service excute() method, which in turn calls another method viewCart().

    In my viewCart() method, I am using following lines of code. This is my client to EJB.

    public void viewCart(Request request) throws Exception {
        CartRemoteInterface cart = null;
        Context ctx1 = null;
        DataSource DSource = null;
        CartHomeInterface cartHomeInterface = null;
        final String LOOKUP_SOURCE = "com/dcx/slsmkt/empadv/ejb/session/ShoppingCart";
        session = request.getSession(true);

        cart = (CartRemoteInterface) session.getAttribute("CartRemoteInterface");
        if (cart != null) {
    // doing nothing, I don't know what I can do here ?? You can help (any suggestion)
        } else {
    // call Statefull session bean
            Hashtable parms = new Hashtable();
            parms.put(Context.INITIAL_CONTEXT_FACTORY, "");
            ctx1 = new InitialContext(parms);
           cartRemoteInterface = cartHomeInterface.create(customerID);
           session.setAttribute("CartRemoteInterface", cartRemoteInterface);

    Question on above code -

    Do i need to put cartRemoteInterface.remove() after setAttribute. If Yes, Why ??

    2. What is the importance of using UserTranscation when designing Shopping Cart application(A statefull session bean).

    Do i need to have it, if YES, what would be default declarative transcation.

    Your information or any feedback will really help me in designing this ..