项目当中使用的配置文件,特别是spring的配置文件,我们需要在应用启动过程中就对配置文件进行初始化,因为很多的constant常量都在spring文件当中配置过,在对配置文件的初始化中,我们可以在web.xml文件当中使用如下方法对其进行初始化声明:
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/conf/application-configs.xml, /WEB-INF/conf/application-dataaccess.xml, ..... /WEB-INF/conf/application-action.xml </param-value> </context-param>
contextConfigLocation 参数定义了要装入的 Spring 配置文件。这样声明了之后,我们就可以在servlet的init方法进行配置文件的初始化,如下:
public void init(ServletConfig config) throws ServletException { servletContext = config.getServletContext(); applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); super.init(config); }初始化过后,我们还要对spring的配置文件的具体bean的配置进行读取以取得具体的bean实例来对业务代码进行处理。这时我们将这些代码写入一个BaseServlet中,以后其他的servlet都继承这个BaseServlet就可以在其他servlet中实现bean的读取了。代码如下:
/** * 返回指定 {@code beanName} 和 {@code clazz} 类型的实例。 * * @param <T> bean 实例类型。 * @param beanName bean的配置 {@code id}。 * @param clazz 类型。 * @return 指定 {@code beanName} 和 {@code clazz} 类型的实例。 */ protected <T> T getBean(String beanName, Class<T> clazz) { if(applicationContext == null) { LOGGER.error("Spring WebApplicationContext 不可用。"); return null; } Object bean = applicationContext.getBean(beanName); if(bean == null) { return null; } if(bean.getClass().equals(clazz)) { return clazz.cast(bean); } else { LOGGER.warn(String.format("%s not found.", clazz.getName())); return null; } }主要还是对Class类的cast方法的应用。cast方法在API中的说法是将一个对象强制转化为该Class对象所表示的类或接口,在这里就是将bean这个对象转化为bean.getClass()后返回的Class对象所表示的类或接口。这句话很模糊,看了cast的源代码,其实最后还是return obj;意思就是返回对象的实例以便之后对其进行相关操作。
当然也可以在具体的servlet中通过WebApplicationContext这个类来getBean()得到具体的在配置文件当中配置的bean。