实现AplicationContextAware接口在Servlet获取所需要bean
1 import org.springframework.beans.BeansException; 2 import org.springframework.context.ApplicationContext; 3 import org.springframework.context.ApplicationContextAware; 4 5 public class SpringContextUtil implements ApplicationContextAware { 6 7 private static ApplicationContext applicationContext; 8 9 @Override 10 public void setApplicationContext(ApplicationContext applicationContext) 11 throws BeansException { 12 applicationContext = applicationContext; 13 } 14 15 public static ApplicationContext getApplicationContext(){ 16 return applicationContext; 17 } 18 19 public static Object getBean(String name){ 20 return applicationContext.getBean(name); 21 } 22 23 public static <T> T getBean(String name, Class<T> requiredClass){ 24 return applicationContext.getBean(name, requiredClass); 25 } 26 27 }
applicationContext.xml中配置一下:
<bean class=”SpringContextUtil” />
1 IAppProductService appProductService = (IAppProductService) SpringContextUtil.getBean("appProductService", AppProductServiceImpl.class);
其实就是注入的方式,Spring中提供一些Aware相关接口,像是BeanFactoryAware、ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,实现这些Aware接口的Bean在被初始之后,可以取得一些相对应的资源,例如实现BeanFactoryAware的Bean在初始后,Spring容器将会注入BeanFactory的实例,而实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入ApplicationContext的实例等等。
Bean取得BeanFactory、ApplicationContextAware的目的是什么,一般的目的就是要取得一些资源的存取、或是使用那些被注入的实例所提供的机制。