Skip to content

Instantly share code, notes, and snippets.

@mmaia
Last active April 15, 2019 21:22
Show Gist options
  • Save mmaia/9fa5cfee05cf04170a2eaa133d15fda4 to your computer and use it in GitHub Desktop.
Save mmaia/9fa5cfee05cf04170a2eaa133d15fda4 to your computer and use it in GitHub Desktop.
Spring boot tricks

Programatically get a spring bean

package io.stockgeeks.metrics;

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

@Service
public class SpringBeanUtil implements ApplicationContextAware {
  private static ApplicationContext context;
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    context = applicationContext;
  }
  public static <T> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment