普通java类获取spring中的bean方法

编写一个工具类

1.实现spring的ApplicationContextAware接口

代码如下:

package com.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * @author luoruiyuan
 *
 */

public class ApplicationUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ApplicationUtil.applicationContext = applicationContext;
	}

	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}
}

2.然后applicationContext.xml中添加如下代码:

<bean id="applicationUtil" class="com.utils.ApplicationUtil"></bean>

提示:ApplicationUtil类使用注解方式的话,第2步可以省略.

3.web.xml添加<load-on-startup>1</load-on-startup>

<!-- Spring前端控制器 -->
<servlet>
	<servlet-name>SpringMVC</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>SpringMVC</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>
 	
<!-- 使用Filter解决中文乱码问题 -->
<filter>
	<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>encodingFilter</filter-name>
	<url-pattern>*.do</url-pattern>
</filter-mapping>

4.调用方法:

GidDao gdao=(GidDao)ApplicationUtil.getBean("gidDao");
List<GidEntity> geList=gdao.getGidInfo(entity);

这样就大功告成了.


(1)