博客详情

SpringContextHolder直接从spring容器中获取bean (原创)

作者: 朝如青丝暮成雪
发布时间:2021-01-16 13:08:42  文章分类:java编程   阅读(3475)  评论(0)


SpringContextHolder直接从spring容器中获取bean


创建类 SpringContextHolder

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

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

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextHelper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
    /**
     * 从spring 上下文中获取bean
     * @param name
     * @param requiredClass
     * @return
     */
    public static  T getBean(String name, Class  requiredClass){
        return applicationContext.getBean(name, requiredClass);
    }
    public  static  T getBean(Class requiredType){
        return applicationContext.getBean(requiredType);
    }

}

使用示例 : 

  MyService myService= SpringContextHolder.getBean(MyService.class);
  String s=myService.hello("张三");
 System.out.println(s);


MyService 是托管自spring容器中的bean 。在任意对象的方法代码中都可以使用SpringContextHolder类的静态方法获取spring容器中的bean .




关键字:  springContext  holder
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号