Dashboard > WG: Programmer's Cafe > ... > Sakai Coding Tips > Getting the ApplicationContext in a spring bean
  WG: Programmer's Cafe Log In | Signup View a printable version of the current page.  
  Getting the ApplicationContext in a spring bean
Added by Aaron Zeckoski, last edited by Aaron Zeckoski on Sep 02, 2006  (view change)
Labels: 
(None)

Here is how to get the ApplicationContext in a spring bean. It can be used to look up other spring beans or search out beans based on their type.

  1. Implement ApplicationContextAware in your bean and add in a setter and private variable for the ApplicationContext
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class SpringBeanThingy implements ApplicationContextAware {
    
    	private ApplicationContext applicationContext;
    	public void setApplicationContext(ApplicationContext applicationContext) {
    		this.applicationContext = applicationContext;
    	}
    
    	// Other methods and stuff here
    }
  2. Make the bean in your spring config file and spring puts in the appcontext for you
    <bean id="appnameSpringBeanThingy"
    	class="org.sakaiproject.appname.spring.SpringBeanThingy" />
  3. Use the ApplicationContext in your methods to look up spring beans (or do whatever you want), for example:
    private List getSpringBeans(String match) {
    	List l = new ArrayList();
    	String[] beanArray = applicationContext.getBeanDefinitionNames();
    	for (int j=0; j<beanArray.length; j++) {
    		if (isMatch(beanArray[j], match)) {
    			l.add(beanArray[j]);
    		}
    	}
    	return l;
    }
    
    private boolean isMatch(String beanName, String mappedName) {
    	return (mappedName.equals(beanName)) ||
    		(mappedName.endsWith("*") && beanName.startsWith(mappedName.substring(0, mappedName.length() - 1))) ||
    		(mappedName.startsWith("*") && beanName.endsWith(mappedName.substring(1, mappedName.length())));
    }

Site running on a free Atlassian Confluence Open Source Project License granted to Sakai Foundation. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.5 Build:#811 Jul 25, 2007) - Bug/feature request - Contact Administrators