spring controller取web.xml中定义的全局变量

在web.xml中定义的全局变量,取的时候可以建一个专门的辅助类来获得。
web.xml中
	<context-param>
		<param-name>apple_apns</param-name>
		<param-value>gateway.push.apple.com</param-value>
		<!-- <param-value>gateway.sandbox.push.apple.com</param-value> -->
	</context-param>

 <listener>
		<listener-class>com.zpf.test.SpringInit.SpringInit</listener-class>
	</listener>


然后编写SpringInit文件
package com.zpf.test.SpringInit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringInit implements ServletContextListener {
    
    private static WebApplicationContext springContext;
  
 
    
    public SpringInit() {
        super();
    }
    
    public void contextInitialized(ServletContextEvent event) {
        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
 
        try{
    		
    		String apple_apns = springContext.getServletContext().getInitParameter("apple_apns");
    		if(apple_apns != null){
    			Constants.PUSH_Host = apple_apns;
    		}
    		
        	
		}catch(Exception e){
			e.printStackTrace();
		}
 
    }
    

    public void contextDestroyed(ServletContextEvent event) {
    }
    
    public static ApplicationContext getApplicationContext() {
        return springContext;
    }

}
//这里已经取到了值了

之后就是编写一个专门调用的Constants
package com.zpf.test.SpringInit;

public class Constants {
	public Constants() {

	}
	public static String PUSH_Host = "";
}


你可能感兴趣的:(java,spring)