com.dotcallservice.manager.ServiceLocator.java Source code

Java tutorial

Introduction

Here is the source code for com.dotcallservice.manager.ServiceLocator.java

Source

package com.dotcallservice.manager;

import javax.servlet.ServletConfig;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dotcall.service.annotation.Service;

/*
 * Copyright 2002-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Movin K
 * @date Aug 21, 2011
 *
 */
public class ServiceLocator {

    private ServletConfig servletConfig;

    private ServiceLocator() {
    }

    public static ServiceLocator getInstance() {
        return ServiceManagerHolder.serviceManager;
    }

    public synchronized void init(ServletConfig servletConfig) {
        this.servletConfig = servletConfig;
    }

    @SuppressWarnings("unchecked")
    public <T> T getService(Class<T> service) {
        if (servletConfig == null) {
            throw new IllegalStateException("ServiceManager has not been initialized !");
        }

        Service daoService = service.getAnnotation(Service.class);
        return (T) getStringBean(daoService.serviceName());
    }

    @SuppressWarnings("unchecked")
    private <K> K getStringBean(String beanName) {
        ApplicationContext ctx = WebApplicationContextUtils
                .getWebApplicationContext(servletConfig.getServletContext());
        return (K) ctx.getBean(beanName);
    }

    private static class ServiceManagerHolder {
        private static ServiceLocator serviceManager = new ServiceLocator();
    }

}