How to use Spring bean reference in static methods


In Spring, we can inject spring beans by using @Autowired annotation.

Builder class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class Builder {

	@Autowired
	private Notifier notifier;

	public void init() {
		notifier.sendMail();
	}

}

Service class

import org.springframework.stereotype.Component;


@Component
public class Notifier {

	public void sendMail() {
		// Business logic
	}

}

In the above example, Spring IoC container creates Notifier Object, Builder object and will also inject Notifier Object ref to Builder object, suppose id init() is static the code won't work.

If we want to use spring bean ref in static methods we need to use ApplicationContextAware interface and override setApplicationContext() and make context object as static.

Spring Configuration class


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


@Component
public class MyContext implements ApplicationContextAware {

	private static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext argApplicationContext) throws BeansException {
		context = argApplicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return context;
	}

	public static <T> T getBean(Class<T> clazz) {
		return context.getBean(clazz);
	}

}

Getting spring bean by using spring context object getBean().

Builder class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class Builder {

	private static Notifier notifier;

	public static void init() {
		notifier = MyContext.getBean(Notifier.class);
		notifier.sendMail();
	}

}

Service class

import org.springframework.stereotype.Component;


@Component
public class Notifier {

	public void sendMail() {
		// Business logic
	}

}