All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.configcenter.spring.utils.SpringInjector Maven / Gradle / Ivy

The newest version!
package com.github.javaclub.configcenter.spring.utils;

import com.github.javaclub.configcenter.client.ConfigException;
import com.github.javaclub.configcenter.spring.config.ConfigPropertySourceFactory;
import com.github.javaclub.configcenter.spring.property.PlaceholderHelper;
import com.github.javaclub.configcenter.spring.property.SpringValueRegistry;
import com.google.common.eventbus.EventBus;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;

public class SpringInjector {

	private static volatile Injector s_injector;
	private static final Object lock = new Object();

	private static Injector getInjector() {
		if (s_injector == null) {
			synchronized (lock) {
				if (s_injector == null) {
					try {
						s_injector = Guice.createInjector(new SpringModule());
					} catch (Throwable ex) {
						ConfigException exception = new ConfigException("Unable to initialize Config Spring Injector!",
								ex);
						throw exception;
					}
				}
			}
		}

		return s_injector;
	}

	public static  T getInstance(Class clazz) {
		try {
			return getInjector().getInstance(clazz);
		} catch (Throwable ex) {
			throw new ConfigException(String.format("Unable to load instance for %s!", clazz.getName()), ex);
		}
	}

	private static class SpringModule extends AbstractModule {
		@Override
		protected void configure() {
			bind(PlaceholderHelper.class).in(Singleton.class);
			bind(ConfigPropertySourceFactory.class).in(Singleton.class);
			bind(SpringValueRegistry.class).in(Singleton.class);
			bind(EventBus.class).in(Singleton.class);
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy