• javaWeb普通类获取ApplicationContext


                 网上看了很多关于获取ApplicationContext的方法,五大方法,但是我用web服务使用成功的就这一个,自己记忆下。

    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    /**
     * 获取ApplicationContext并调用
     */
    public class StartListener implements ServletContextListener{
    	//这是一个类,就是通过xml方式能调用到这个类。必须是静态修饰
    	private static ItemService itemService;
    	
    	public StartListener(){
    		super();
    	}
    
    	@Override
    	public void contextInitialized(ServletContextEvent sce) {
    		// TODO Auto-generated method stub
    		WebApplicationContext springContext=WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());//获取初始化的上下文
    		itemService = ( ItemService ) springContext.getBean( "item" );//可以传形参的方式改变想要获取的bean
    	}
    	
    	/**
    	 * 创建目录,这是调用上面类中的方法
    	 * @param mkdirName
    	 * @return
    	 */
    	public String mkdir(String mkdirName){
    		System.out.println("调用创建目录方法!!");
    		return itemService.mkdir(mkdirName);
    	}
    	@Override
    	public void contextDestroyed(ServletContextEvent sce) {
    		// TODO Auto-generated method stub
    		//销毁
    	}
    	
    
    
    }

    xml中需要的设置:

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app id="WebApp_1530018094941">
    	<display-name>Archetype Created Web Application</display-name>
    
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:hsf-consumer-beans.xml</param-value>
    	</context-param>
            //用于监听刚刚配置的类
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	<listener>
    		<listener-class>com.alibaba.edas.carshop.detail.StartListener</listener-class>
    	</listener> 
    	//下面是接口
    	<servlet id="Servlet_1531272320787">
    		<servlet-name>IndexServlet</servlet-name>
    		<servlet-class>com.alibaba.edas.carshop.detail.IndexServlet</servlet-class>
    	</servlet>
    	<servlet-mapping id="ServletMapping_1531272320723">
    		<servlet-name>IndexServlet</servlet-name>
    		<url-pattern>/index.htm</url-pattern>
    	</servlet-mapping>
    
    </web-app>

    关于获取ApplicationContext的方法,适用于我的是这个方法,其他几个方式你们也可以去试试。总共5大方法,总有一款适合你。



  • 相关阅读:
    VSCode集成TypeScript编译
    http模拟登陆及发请求
    1​1​.​0​5​9​2​M​晶​振​与12M晶振
    单片机定时器2使用
    Altium Designer 小记
    sql-mysql
    java英文缩写
    Altium Design
    Tomcat使用
    jar/war/ear文件的区别
  • 原文地址:https://www.cnblogs.com/wanchen-chen/p/12934122.html
Copyright © 2020-2023  润新知