欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

整合spring项目之 加载 Spring 配置文件的两种方式

程序员文章站 2024-01-20 17:26:22
...

在过滤器中实现

package com.beyond.nothing.filters;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/")
public class EncodingFilter implements Filter {

    private static Log log = LogFactory.getLog(EncodingFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 加载spring 配置文件
        new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        log.info("EncodingFilter init success !!");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    }

    @Override
    public void destroy() {

        log.info("EncodingFilter destroy success !!");
    }
}

在web.xml 中通过 监听器实现加载

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

<!--  加载 上下文配置文件的第二种方式-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>