---
title: "在Servlet直接获取Spring框架中的Bean"
author: "superloafer"
date: "2008-10-21T14:58:12Z"
tags: []
slug: "servlet-spring-bean"
draft: false
lastmod: "2008-10-21T14:58:12Z"
id: 255876
url: "https://superloafer.iteye.com/blog/255876"
---

有时候写个小应用，不想搞那么复杂，但又想揩点Spring的油，可以省去一些麻烦。在Application环境下，直接new一个ApplicationContext的实现类，把配置文件传进去然后那些Bean们就可以任凭处置了。同时，在WebApplication环境下，也可以在Servlet中直接获取Spring配置文件的Bean，有两种方法：
1. 在获取要使用的bean之前拿到当前ServletContext的 ApplicationContext，之后你想要什么尽管get便是了：

```java

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object myDao = context.getBean("daoBeanName");

```


2.

```xml

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
		<property name="attributes">
			<map>
				<entry key="bean1">
					<ref bean="existingBean1"/>
				</entry>
				<entry key="bean2">
					<ref bean="existingBean2"/>
				</entry>
			</map>
		</property>
	</bean>

```

然后在Servlet里面就可以通过获取属性的方式getServletContext().getAttribute("bean1")来获得Beans的使用权了.