1. 程式人生 > >獲取spring的例項物件

獲取spring的例項物件

首先要繼承ApplicationContextAware來獲取上下文:ApplicationContext

public class SpringContextUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
	{
		SpringContextUtils.applicationContext = applicationContext;
	}

//	各種方法獲取例項
	public static Object getBean(String beanName)
	{
		if (applicationContext != null)
			return applicationContext.getBean(beanName);
		
		return null;
	}

	public static <T> T getBean(Class<T> clazz)
	{
		if (applicationContext != null)
			return applicationContext.getBean(clazz);
		
		return null;
	}
	
	public static <T> T getBean(String beanName, Class<T> clazz)
	{
		if (applicationContext != null)
			return clazz.cast(getBean(beanName));
		
		return null;
	}


然後還需在 xml 檔案裡面加上此類:

<bean class="cn.base.mvc.SpringContextUtils" />