问题
I have a Spring application that can use two different persistence API:
- Spring Data JPA
- Spring Data Neo4j
When using Spring Data JPA, I need to declare the "OpenEntityManagerInViewFilter" in "web.xml" to do lazy loading:
<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>
The problem is that I cannot keep this filter enabled when using Spring Data Neo4j. Leaving it enabled leads to the following runtime error:
No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
I want to choose which database to use with a Spring profile (e.g. spring.profiles.active=relational-database
or spring.profiles.active=graph-database
).
Question: how can I enable the "OpenEntityManagerInViewFilter" when profile is "relational-database", and disable it when profile is "graph-database"?
Thanks!
Related questions :
- How to conditionally enable/disable filter in web.xml but I'm not using
DelegatingFilterProxy
.
回答1:
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.
来源:https://stackoverflow.com/questions/30800916/enabling-disabling-a-web-xml-filter-using-a-spring-profile