ApplicationContextAware的使用原理

来源:互联网 发布:支付宝如何登陆淘宝 编辑:程序博客网 时间:2024/06/05 09:50

作用

继承ApplicationContextAware接口,可以在Tomcat启动后获取Spring的ApplicationContext,从而可以获取bean对象.

案例

定义Utils类,继承接口

注意:我们在使用SpringUtils的时候,不用调用其set方法,因为在web.xml中配置监听器后,Spirng将会自动调用set方法,完成applicationContext的赋值

public class SpringUtils implements ApplicationContextAware{    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext arg0) throws BeansException    {        applicationContext = arg0;    }    public static Object getBeanById(String id)    {        return applicationContext.getBean(id);    }}

web.xml中的配置:

  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:*.xml</param-value>  </context-param>

Servlet中调用:

    private DependTest dependTest = (DependTest) SpringUtils.getBeanById("dependTest");    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws javax.servlet.ServletException, IOException    {        doGet(request, response);    }    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)            throws javax.servlet.ServletException, IOException    {        dependTest.test();    }
原创粉丝点击