【转】在Servlet中访问Spring管理下的bean

提供一个思路,仅做参考web.xml:

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:springbeans.xml</param-value>
</context-param>
<listener>
       <listener-class>lnx.base.InitPlatformLoader</listener-class></listener>

 InitPlatformLoader.java :

package lnx.base;

import javax.servlet.ServletContextEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 平台初始化类
 */
public class InitPlatformLoader extends ContextLoaderListener {
    protected final Log logger = LogFactory.getLog(getClass());

    public void contextInitialized(ServletContextEvent event) {
        logger.info("初始化平台...");
        super.contextInitialized(event);
        String path = event.getServletContext().getRealPath("/");
        logger.debug("系统部署根路径:" + path);
        Platform.getInstance().setWebPath(path);
        // 初始化Support中Spring的CTX
        ApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(event.getServletContext());
        Platform.getInstance().setApplicationContext(ctx);
        logger.info("初始化完成...");
    }
}

 Platform.java:

package lnx.base;

import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

/**
* 平台,为各级提供spring的getbean的方法
*
* @author Feng
*/
public class Platform {
    private static Platform ourInstance = new Platform();

    public static Platform getInstance() {
        return ourInstance;
    }

    private Platform() {
    }

    private ApplicationContext applicationContext = null;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据BeanName获得Bean
     *
     * @param beanName sping配置的id
     * @return 符合条件的bean
     */
    public Object getBean(String beanName) {
        Assert.hasText(beanName);
        return this.applicationContext.getBean(beanName);
    }

    // 平台部署的根物理路径
    private String WebPath;

    /**
     * 获得平台部署的根物理路径
     *
     * @return 根物理路径
     */
    public String getWebPath() {
        return WebPath;
    }

    /**
     * 设置根物理路径
     *
     * @param webPath 根物理路径
     */
    public void setWebPath(String webPath) {
        WebPath = webPath;
    }
}

 用法:

Platform.getInstance().getBean("bean的name");

来自:http://bbs.langsin.com/thread-4286-1-89.html 非常感谢!

相关推荐