Skip to content

Instantly share code, notes, and snippets.

@featheredtoast
Created November 19, 2016 22:11
Show Gist options
  • Save featheredtoast/3ed9df59b1879d40cd775054faf36a34 to your computer and use it in GitHub Desktop.
Save featheredtoast/3ed9df59b1879d40cd775054faf36a34 to your computer and use it in GitHub Desktop.
spring autowire stuff
/**
* Helper class which is able to autowire a specified class. It holds a static reference to the {@link org
* .springframework.context.ApplicationContext}.
*/
@Component
public final class AutowireHelper implements ApplicationContextAware {
private static final AutowireHelper INSTANCE = new AutowireHelper();
private static ApplicationContext applicationContext;
private AutowireHelper() {
}
/**
* Tries to autowire the specified instance of the class if one of the specified beans which need to be autowired
* are null.
*
* @param classToAutowire the instance of the class which holds @Autowire annotations
* @param beansToAutowireInClass the beans which have the @Autowire annotation in the specified {#classToAutowire}
*/
public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
for (Object bean : beansToAutowireInClass) {
if (bean == null) {
applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
return;
}
}
}
public static void autowire(Object classToAutowire) {
List<Object> beansToAutowireInClass = new ArrayList<Object>();
for(Field field : classToAutowire.getClass().getDeclaredFields())
{
if (field.isAnnotationPresent(Inject.class))
{
try {
field.setAccessible(true);
Object o = field.get(classToAutowire);
beansToAutowireInClass.add(o);
} catch (IllegalArgumentException e) {
Log.warn("illegal argument", e);
} catch (IllegalAccessException e) {
Log.warn("illegal access", e);
}
}
}
for (Object bean : beansToAutowireInClass) {
if (bean == null) {
applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
return;
}
}
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
AutowireHelper.applicationContext = applicationContext;
}
/**
* @return the singleton instance.
*/
public static AutowireHelper getInstance() {
return INSTANCE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment