Created
November 19, 2016 22:11
-
-
Save featheredtoast/3ed9df59b1879d40cd775054faf36a34 to your computer and use it in GitHub Desktop.
spring autowire stuff
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
/** | |
* 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