• SpringMvc 获取ApplicationContext


    有时,我们不通过Controller层进入Service层,比如同步数据,任务,以及文件上传共通Handler对文件处理后保存数据等都会由一个非Controller类调用Service。

    这时候如果new Service会因为没有事务控制也没法打开jdbc连接,也不满足spring的bean管理。因此需要获取到spring创建的service。

    ApplicationContext会在spring的扫描时加入进来。

    获取方式:

    需要创建一个类(例:ContextUtils)实现ApplicationContextAware接口。

    会自动实现一个setApplicationContext的方法,spring在扫描完毕类后,调用ApplicationContextAware接口的实现类,自动传递applicationContext到这个类中。

    创建一个自己的getBean方法获取自己想要的类。

    public class ContextUtils implements ApplicationContextAware {
        
        private static ApplicationContext context;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
        }
        
        public static Object getBean(String strBeanName) {
            return context.getBean(strBeanName);
        }
    
    }

    在dispatch-context.xml中加入自己写的ContextUtils类。

    <!-- ContextUtils -->
    <bean id="contextUtils" class="com.pccw.solutions.retire.common.utils.ContextUtils"></bean>

    这样就可以在自己想要的任何位置获取Bean.

  • 相关阅读:
    NOI2.5 4980:拯救行动
    NOI2.5 1490:A Knight's Journey
    NOI2.5 8465:马走日
    考试题目“部落卫队”
    考试题目“笨笨的西瓜种植”
    考试题目“笨笨玩游戏”
    NOI4.6 1455:An Easy Problem
    NOI2.5 1253:Dungeon Master
    NOI2.2 8758:2的幂次方表示
    NOI2.5 1817:城堡问题
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/8143646.html
Copyright © 2020-2023  润新知