/ Published in: Java
A very simple way of getting bean instances from Spring context without casting returned object, the assumption is that the bean id's are matching the classes names.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
//The interface: public interface AppContainer { <T> T getIns(Class<T> clazz); } //The implementation: import static org.apache.commons.lang.StringUtils.uncapitalize; public class DefaultAppContainer implements AppContainer { private ApplicationContext factory; public DefaultAppContainer() { factory = new ClassPathXmlApplicationContext("spring/application.xml"); } public <T> T getIns(Class<T> clazz) {// this should work for 90% of the casses return (T) factory.getBean(uncapitalize(clazz.getSimpleName())); } return factory.getBean(uncapitalize(clazz.getSimpleName())); } }