Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

@Autowired's magic however can only be used on Spring managed beans (instantiated objects that are managed by Spring).  However, there 's are many situations where you might need access to a Spring bean from non-Spring manged classes and POJO's (Plain Old Java Objects).

...

Code Block
languagejava
titleSpringContext.java
linenumberstrue
package com.adfaspace.jay.app;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {
	
	private static ApplicationContext context;
	
	/**
	 * Returns the Spring managed bean instance of the given class type (if it exists).
	 * Returns null otherwise.
	 * @param beanClass
	 * @return
	 */
	public static <T extends Object> T getBean(Class<T> beanClass) {
		return context.getBean(beanClass);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		
		// store ApplicationContext reference to access required beans later on
		SpringContext.context = context;
	}
}

...

Code Block
languagejava
MyBeanClass myBeanClassmyBeanInstance = SpringContext.getBean(MyBeanClass.class);

...