it.cavallefano.abstractfactoryspring.factory.ObjFactory.java Source code

Java tutorial

Introduction

Here is the source code for it.cavallefano.abstractfactoryspring.factory.ObjFactory.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 it.cavallefano.abstractfactoryspring.factory;

import it.cavallefano.abstractfactoryspring.concrete.Car;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 *
 * @author s.cavallotto
 */
public class ObjFactory implements ApplicationContextAware {

    private static ApplicationContext mApplicationContext;

    private static Map<String, String> processorBeanMap = new HashMap<String, String>();

    public static Car getCar(String carName) {
        String beanName = processorBeanMap.get(carName);
        Car bean = (Car) mApplicationContext.getBean(beanName);
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        mApplicationContext = ac;

        Map<String, Car> processorMap = mApplicationContext.getBeansOfType(Car.class);
        if (processorMap.isEmpty()) {
            Error noProcessorError = new Error("No Car configured. Check Spring Context");
            throw noProcessorError;
        }
        Set<Entry<String, Car>> processorEntrySet = processorMap.entrySet();

        Iterator<Entry<String, Car>> iterator = processorEntrySet.iterator();

        while (iterator.hasNext()) {
            Entry<String, Car> entry = iterator.next();

            processorBeanMap.put(entry.getValue().getClass().getSimpleName(), entry.getKey());
        }
    }
}