Skip to content

Instantly share code, notes, and snippets.

@nacx
Created June 23, 2011 08:58
Show Gist options
  • Save nacx/1042181 to your computer and use it in GitHub Desktop.
Save nacx/1042181 to your computer and use it in GitHub Desktop.
Spring static Bean loader to load beans outside the Servlet or Sprign context
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public final class BeanLoader implements ApplicationContextAware
{
private static BeanLoader instance;
private ApplicationContext applicationContext;
private BeanLoader()
{
}
public static BeanLoader getInstance()
{
if (instance == null)
{
instance = new BeanLoader();
}
return instance;
}
public <T> T getBean(final Class<T> beanClass)
{
if (applicationContext == null)
{
throw new IllegalStateException("ApplicationContext has not been set. BeanLoader must be configured in Spring'sapplication context in order to be used.");
}
return BeanFactoryUtils.beanOfType(applicationContext, beanClass);
}
@SuppressWarnings("unchecked")
public <T> T getBean(final String beanName, final Class<T> expectedClass)
{
if (applicationContext == null)
{
throw new IllegalStateException("ApplicationContext has not been set. BeanLoader must be configured in Spring'sapplication context in order to be used.");
}
return (T) applicationContext.getBean(beanName);
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext)
{
this.applicationContext = applicationContext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment