【转】在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");
相关推荐
编程点滴 2020-07-29
itjavashuai 2020-07-04
凯哥Java 2020-04-25
yupi0 2020-10-10
spring 2020-08-18
幸运小侯子 2020-07-05
qingjiuquan 2020-06-29
shushan 2020-06-25
小鱿鱼 2020-06-22
咻pur慢 2020-06-18
melonjj 2020-06-17
qingjiuquan 2020-06-13
neweastsun 2020-06-05
小鱿鱼 2020-06-05
mxcsdn 2020-05-31
吾日五省我身 2020-05-27
牧场SZShepherd 2020-05-27