Enabling/disabling a web.xml filter using a Spring profile

前端 未结 1 1991
别跟我提以往
别跟我提以往 2020-12-10 20:59

I have a Spring application that can use two different persistence API:

  • Spring Data JPA
  • Spring Data Neo4j

When using Spring Data JPA, I

相关标签:
1条回答
  • 2020-12-10 21:43

    Ok, I sorted this out. My new "web.xml" uses DelegatingFilterProxy instead of org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter:

    <filter>
        <filter-name>toggleOpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>toggleOpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    Then in my ApplicationContext, I create a bean named "toggleOpenEntityManagerInViewFilter" (which is the filter-name value). The trick is to instanciate a different class depending on the Spring profile:

    <beans profile="graph-database">
        <bean id="toggleOpenEntityManagerInViewFilter" class="my.project.dal.utils.spring.DoNothingFilter"/>
    </beans>
    <beans profile="relational-database">
        <bean id="toggleOpenEntityManagerInViewFilter" class="org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter"/>
    </beans>
    

    The my.project.dal.utils.spring.DoNothingFilter is defined as:

    public class DoNothingFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
        }
    }
    

    This seems to work.

    0 讨论(0)
提交回复
热议问题