Enabling/disabling 使用 Spring 配置文件的 web.xml 过滤器

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

我有一个 Spring 应用程序可以使用两种不同的持久性 API:

当使用Spring数据JPA时,我需要在"web.xml"中声明"OpenEntityManagerInViewFilter"来做延迟加载:

<filter>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

问题是我无法在使用 Spring Data Neo4j 时启用此过滤器。启用它会导致以下运行时错误:

No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

我想选择哪个数据库用于 Spring 配置文件(例如 spring.profiles.active=relational-databasespring.profiles.active=graph-database)。

问题:如何在配置文件为"relational-database"时启用"OpenEntityManagerInViewFilter",并在配置文件为"graph-database"时禁用它?

谢谢!

相关问题:

好的,我解决了这个问题。我的新 "web.xml" 使用 DelegatingFilterProxy 而不是 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>

然后在我的 ApplicationContext 中,我创建了一个名为 "toggleOpenEntityManagerInViewFilter" 的 bean(即 filter-name 值)。诀窍是根据 Spring 配置文件实例化不同的 class:

<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>

my.project.dal.utils.spring.DoNothingFilter定义为:

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() {
    }
}

这似乎有效。