1. 程式人生 > >【Spring-boot】通過ApplicationContextAware獲取spring管理物件

【Spring-boot】通過ApplicationContextAware獲取spring管理物件

  • 用途
    1,在filter中使用servcie

  • 程式碼

@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        if
(SpringUtils.applicationContext == null) { SpringUtils.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 根據name * * @param name * @return */ public
static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 根據型別 * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(
clazz); } public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }