Versions Compared

Key

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

...

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
		setContext(context);
	}  	

 	/**
	 * Private method context setting (better practice for setting static field in a bean 
	 * instance - see comments of this article).
	 */
	private static synchronized void setContext(ApplicationContext context) {
    			SpringContext.context = context;
  	} 
}

That's it... all you need to provide access of Spring managed beans to POJO classes.

...