当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>当然,这样子的话只会读取默认路径下的application.xml配置文件的。如果需要读取特定路径下的配置文件。需要在web.xml中
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/app-context.xml</param-value> </context-param>注意:<param-name>contextConfigLocation</param-name>是不能改变的。
public class AppUtil implements ApplicationContextAware为方法类AppUtil增加一个静态的成员ApplicationContext类型的对象。以后方法类AppUtil获取ApplicationContext,就是通过读取这个
private static ApplicationContext appContext;实现ApplicationContextAware接口的默认方法:
public void setApplicationContext(ApplicationContext paramApplicationContext) throws BeansException { appContext = paramApplicationContext; }3、在spring的配置文件中,注册方法类AppUtil
<bean id="appUtil" class="com.htsoft.core.util.AppUtil"/>4、使用静态的成员ApplicationContext类型的对象,appContext,来调用其他bean。在方法类AppUtil中增加如下方法:
public static Object getBean(String paramString) { return appContext.getBean(paramString); }那么,在方法类AppUtil中就能够灵活地调用其他任何一个bean了,例如:
CompanyService localCompanyService = (CompanyService)getBean("companyService");注:配置文件中关于companyService的内容:
<bean id="companyService" class="com.kaiwii.service.system.impl.CompanyServiceImpl"> <constructor-arg index="0" ref="companyDao"/> </bean>