web项目( spring )启动后,SpringContextUtils的applicationContext属性会自动初始化(不必 new ClassPathXmlApplicationContext("applicationContext.xml")),于是可以自行编写一些静态方法从 applicationContext 中获取bean了。
package org.springside.modules.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtils
implements ApplicationContextAware
{
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context)
{
applicationContext = context;
}
public static ApplicationContext getApplicationContext()
{
if (applicationContext == null)
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil");
return applicationContext;
}
public static <T> T getBean(String name)
{
return applicationContext.getBean(name);
}
}
<bean id="springContextUtils" class="org.springside.modules.utils.SpringContextUtils" />