Struts 2 + Spring 2 + JPA 的配置补充
搭建方法主要参考struts2 guide中的Struts 2 + Spring 2 + JPA + AJAX(struts.apache.org/2.0.9/docs/struts-2-spring-2-jpa-ajax.html)文档。
关于用到的类库和构建方法参考那篇文档即可。这里要补充一下,为了方便进行测试,最好把spring-mock.jar也加进来。这样就可以使用AbstractJpaTests对象了,可以很好支持对lazy-load的测试,下边是一个例子:
测试基类:
java 代码
- import org.springframework.test.jpa.AbstractJpaTests;
- public abstract class BaseJpaTestCase extends AbstractJpaTests {
- protected String[] getConfigLocations() {
- return new String[] {
- "file:/WebAppRoot/WEB-INF/applicationContext.xml",
- "file:/WebAppRoot/WEB-INF/applicationContext-service.xml" };
- }
- }
具体的测试类:
java 代码
- public class UserRoleServiceTest extends BaseJpaTestCase {
- private UserRoleService userRoleService;
- public void setUserRoleService(UserRoleService userRoleService) {
- this.userRoleService = userRoleService;
- }
- @Test
- public void testRemove() {
- UserRole entity = new UserRole("some role name");
- userRoleService.save(entity);
- UserRole persistedEntity = userRoleService.find(entity.getId());
- assertEquals(entity.getName(), persistedEntity.getName());
- userRoleService.remove(persistedEntity .getId());
- assertNull(userRoleService.find(persistedEntity .getId()));
- }
- }
测试类不需要在spring配置文件中进行说明,service对象会被自动的注入,非常的方便。
以前用hibernate的时候,Spring提供了OpenSessionInViewFilter来解决在view层的lazy-load问题。而使用jpa进行封装之后,可以使用OpenEntityManagerInViewFilter来达到同样的目的。
在web.xml中进行同样的配置即可:
xml 代码
- <filter>
- <filter-name>entityManagerFilterfilter-name>
- <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilterfilter-class>
- filter>
- <filter-mapping>
- <filter-name>entityManagerFilterfilter-name>
- <url-pattern>*.actionurl-pattern>
- filter-mapping>
使用JPA的确是一个不错的选择,现在系统已经可以完全和所使用的持久化框架脱离关系了,虽然我可能会一直是用hibernate,不过在将来多一个选择总是不会错的。
不灵活是一定的,不过个人喜欢这种与特定框架解耦的感觉。就像jdbc,虽然牺牲了部分灵活性,却带来了巨大的好处。
解决了,原来struts.xml里action的class要配成Spring里的bean的名称!唉,配置如何能做到“强类型”啊
按照这篇文章配置,我碰到了一个问题:文章里说将service从构造函数注入Action中,但是我运行后Struts报错说必须要有无参数的构造函数,我加了无参数构造函数后,service就空指针,说明action并没有从Spring初始化,不知道是什么原因。是不是什么地方没配好?