We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

narkisr on 01/21/08


Tagged

java generics spring Context


Versions (?)


A simple solution for "castless" spring application context


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.


  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 

You need to login to post a comment.