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

com.gitlab.spacetrucker.modularspringcontexts.SingletonBeanImportFactoryBean Maven / Gradle / Ivy

There is a newer version: 0.3.2
Show newest version
package com.gitlab.spacetrucker.modularspringcontexts;

import java.text.MessageFormat;

import javax.annotation.PostConstruct;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * A factory bean for creating singleton imports of beans defined in an
 * {@link ApplicationContext} into the ApplicationContext that is defining this
 * import. The {@code import} element defined in {@code modular-spring-contexts.xsd} will
 * trigger the initialization of an instance of this bean when using the default
 * spring namespace resolution of spring xml context authoring.
 */
public class SingletonBeanImportFactoryBean extends AbstractFactoryBean implements ApplicationContextAware {

	private ApplicationContext targetContext;
	private String sourceModuleName;
	private String sourceBeanName;
	private ApplicationContext sourceModule;

	@PostConstruct
	private void afterConstruction() {
		try {
			this.sourceModule = targetContext.getBean(sourceModuleName, ApplicationContext.class);
		} catch (NoSuchBeanDefinitionException e) {
			throw new NoSuchBeanDefinitionException(sourceModuleName, MessageFormat
					.format("No bean named ''{0}'' is defined in module ''{1}''.", sourceModuleName,
							targetContext.getId()));
		}
	}

	@Override
	public Class getObjectType() {
		if (sourceModule == null) {
			/*
			 * This method is called during very early initialization stages of
			 * prototype bean instances of this class. At this point no
			 * properties are set and we have no chance to find the type for the
			 * bean created by this instance. So just return null as the
			 * contract of this method suggests.
			 */
			return null;
		}
		return sourceModule.getType(sourceBeanName);
	}

	@Override
	protected Object createInstance() throws Exception {
		return sourceModule.getBean(sourceBeanName);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.targetContext = applicationContext;
	}

	public void setSourceBeanName(String sourceBeanName) {
		this.sourceBeanName = sourceBeanName;
	}

	public void setSourceModuleName(String sourceModuleName) {
		this.sourceModuleName = sourceModuleName;
	}

}