首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

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

2012-08-21 
【转】在Servlet中访问Spring管理下的bean提供一个思路,仅做参考web.xml:?context-paramparam-nameconte

【转】在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?非常感谢!

热点排行