首页 > 编程语言 > 详细

获取Spring Bean

时间:2019-02-20 16:25:58      阅读:138      评论:0      收藏:0      [点我收藏+]

1.创建MyContextLoaderListener

       继承ContextLoaderListener,重写contextInitialized方法

    ServletContextListener是对ServeltContext的一个监听.servelt容器启动,serveltContextListener就会调用contextInitialized方法.在方法里面调用event.getServletContext()可以获取ServletContext,ServeltContext是一个上下文对象,他的数据供所有的应用程序共享,进行一些业务的初始化servelt容器关闭,serveltContextListener就会调用contextDestroyed.

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MyContextLoaderListener extends ContextLoaderListener { private static ApplicationContext context; public static ApplicationContext getApplicationContext() { return context; } /* * (non-Javadoc) * * @see * org.springframework.web.context.ContextLoaderListener#contextInitialized * (javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); ServletContext servletContext = event.getServletContext(); WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); context = applicationContext; } @Override public void contextDestroyed(ServletContextEvent event) { super.contextDestroyed(event); } }

2.创建SpringContext

 

import org.springframework.context.ApplicationContext;
import xxx.xxx.MyContextLoaderListener;


public class SpringContext {
   
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {

        ApplicationContext context = IHomeContextLoaderListener.getApplicationContext();
        if (context == null) {
            return null;
        }
        return (T) context.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> classsz) {
        ApplicationContext context = IHomeContextLoaderListener.getApplicationContext();
        if (context == null) {
            return null;
        }
        return (T) context.getBean(name, classsz);
    }

    public static <T> T getBean(Class<T> classsz) {
        ApplicationContext context = IHomeContextLoaderListener.getApplicationContext();
        if (context == null) {
            return null;
        }
        return (T) context.getBean(classsz);
    }
}

 

 

 

3.修改web.xml

 <listener>
    <listener-class>xxx.xxx.MyServletContextListener</listener-class>
  </listener>

4.获取Spring Bean

  SpringContext.get(xxx.class)

获取Spring Bean

原文:https://www.cnblogs.com/acelly/p/10407211.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!