Created
June 23, 2011 08:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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