Skip to content

Instantly share code, notes, and snippets.

@rbaul
Created January 2, 2019 18:49
Show Gist options
  • Save rbaul/6a386e097984c1c8fe22e8caae191f26 to your computer and use it in GitHub Desktop.
Save rbaul/6a386e097984c1c8fe22e8caae191f26 to your computer and use it in GitHub Desktop.
Spring Bean Util for get specific bean from application/request context
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.Objects;
@Service
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* Get Bean from application context
*
* @param beanClass - class of the Bean
* @param <T> - type of bean
* @return - object bean
*/
public static <T> T getBean(Class<T> beanClass) {
return Objects.nonNull(context) ? context.getBean(beanClass) : null;
}
/**
* Get Bean from request context
*
* @param beanClass - class of the Bean
* @param <T> - type of bean
* @return - object bean
*/
public static <T> T getRequestBean(Class<T> beanClass) {
return isRequestScope() ? getBean(beanClass) : null;
}
/**
* @return - true if it's request scope
*/
public static boolean isRequestScope() {
return Objects.nonNull(RequestContextHolder.getRequestAttributes());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment