• 获取spring上下文的bean 工具类


    有些场景我们不属于controller,service,dao,但是我们需要从spring中得到spring容器里面的bean。这时候我们需要一个类继承

    ApplicationContextAware  实现这个类的set方法,set的参数就是spring的上下文,然后我们就可以  为所欲为了~~~

    话不多说,上代码。

    ApplicationContextHelper.java
    package com.mmall.common;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    @Component("applicationContextHelper")
    public class ApplicationContextHelper implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        public void setApplicationContext(ApplicationContext context) throws BeansException {
            applicationContext = context;
        }
    
        public static <T> T popBean(Class<T> clazz) {
            if (applicationContext == null) {
                return null;
            }
            return applicationContext.getBean(clazz);
        }
    
        public static <T> T popBean(String name, Class<T> clazz) {
            if (applicationContext == null) {
                return null;
            }
            return applicationContext.getBean(name, clazz);
        }
    }
    View Code
    上面的工具类中包括两个,一个是根据class得到bean,一个是通过name和class得到bean,为了防止多继承的情况。。。

    最后 我们还需要在spring-servlet.xml中声明一下
    <bean class="com.mmall.common.ApplicationContextHelper" lazy-init="false" />
    
    

    ok  !!!!!!!!!!!

     
     
  • 相关阅读:
    Mongodb 查询时间类型
    Python更新所有pip package
    Python selenium on windows
    Redis cluster setup on windows
    CAP定理(theorem)
    error: Microsoft Visual C++ 14.0 is required when installing python package
    using RNGCryptoServiceProvider to generate random string
    <map>的使用
    二维vector的使用
    vector做形参时的三种传参方式
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/8647763.html
Copyright © 2020-2023  润新知