A simple solution for "castless" spring application context


/ Published in: Java
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. //The interface:
  2.  
  3. public interface AppContainer {
  4.  
  5. <T> T getIns(Class<T> clazz);
  6.  
  7. Object getInstanceSkipCast(Class clazz);
  8.  
  9. }
  10.  
  11.  
  12. //The implementation:
  13.  
  14. import static org.apache.commons.lang.StringUtils.uncapitalize;
  15.  
  16. public class DefaultAppContainer implements AppContainer {
  17.  
  18. private ApplicationContext factory;
  19.  
  20. public DefaultAppContainer() {
  21. factory = new ClassPathXmlApplicationContext("spring/application.xml");
  22. }
  23.  
  24. public <T> T getIns(Class<T> clazz) {// this should work for 90% of the casses
  25. return (T) factory.getBean(uncapitalize(clazz.getSimpleName()));
  26. }
  27.  
  28. public Object getInstanceSkipCast(Class clazz) {
  29. return factory.getBean(uncapitalize(clazz.getSimpleName()));
  30. }
  31.  
  32.  
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.