• 实现ApplicationContextAware的好处


    public class SpringContextHolder implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringContextHolder.applicationContext = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext() {
            assertApplicationContext();
            return applicationContext;
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String beanName) {
            assertApplicationContext();
            return (T) applicationContext.getBean(beanName);
        }
    
        public static <T> T getBean(Class<T> requiredType) {
            assertApplicationContext();
            return applicationContext.getBean(requiredType);
        }
    
        private static void assertApplicationContext() {
            if (SpringContextHolder.applicationContext == null) {
                throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
            }
        }
    
    }
    

    好处

    1.使用 SpringContextHolder.getBean(MembersService.class)得到spring托管的bean
    2.即使这个类不受spring容器的托管,也可以通过巧妙的static所有实例共享的方式获得受托管的bean,使后续方法调用受spring管理。

  • 相关阅读:
    android dumpsys meminfo 详解
    效率思维模式与Zombie Scrum
    Mac中Run快捷键修改
    airtest+pytest实战教程05—登录智学网app
    对select函数的理解
    Appium定位元素
    Hack The Box——ServMon
    Oracle DG常用视图与运维护常用操作
    Oracle EBS订单的流程(Order->AR)
    财经法规与会计职业道德
  • 原文地址:https://www.cnblogs.com/imjamin/p/10627284.html
Copyright © 2020-2023  润新知