Child pages
  • Getting the ApplicationContext in a spring bean
Skip to end of metadata
Go to start of metadata

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())));
    }
    
  • No labels