net.vnt.ussdapp.util.Context.java Source code

Java tutorial

Introduction

Here is the source code for net.vnt.ussdapp.util.Context.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.vnt.ussdapp.util;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 *
 * @author doclv
 */
public class Context implements ApplicationContextAware {

    private static Context instance;
    private static ApplicationContext applicationContext;

    private Context() {
        Context.instance = this;
    }

    public static Context getInstance() {
        return instance;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Context.applicationContext = applicationContext;
    }

    public Object getBean(String id) {
        return applicationContext.getBean(id);
    }

    public List<Object> getBeansOfType(@SuppressWarnings("rawtypes") Class clazz) {
        List<Object> beans = new ArrayList<Object>();
        for (String name : applicationContext.getBeanNamesForType(clazz)) {
            beans.add(getBean(name));
        }
        return beans;
    }

    public Object getBean(Class clazz) {
        String id = clazz.getName();

        if (!applicationContext.containsBean(id)) {
            id = id.substring(id.lastIndexOf('.') + 1);
        }

        return getBean(id);
    }

}