spring 测试类test测试方法
实例掩码地址为:孔浩组织结构设计
web.xml配置文件:
1 <!-- Spring 的监听器可以通过这个上下文参数来获取beans.xml的位置 --> 2 <context-param> 3 <param-name>contextConfigLocation</param-name> 4 <param-value>classpath*:beans.xml</param-value> 5 </context-param>
测试类
1 package org.konghao.service; 2 3 import javax.inject.Inject; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.junit.After; 8 import org.junit.Before; 9 import org.junit.Test; 10 import org.junit.runner.RunWith; 11 import org.konghao.sys.org.iservice.IInitService; 12 import org.springframework.orm.hibernate4.SessionHolder; 13 import org.springframework.test.context.ContextConfiguration; 14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 import org.springframework.transaction.support.TransactionSynchronizationManager; 16 17 @RunWith(SpringJUnit4ClassRunner.class) 18 @ContextConfiguration("/beans.xml") 19 public class TestInitService { 20 @Inject 21 private IInitService initService; 22 @Inject 23 private SessionFactory sessionFactory; 24 25 @Before 26 public void setUp() { 27 //此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu 28 Session s = sessionFactory.openSession(); 29 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s)); 30 //SystemContext.setRealPath("D:\\teach_source\\class2\\j2EE\\dingan\\cms-da\\src\\main\\webapp"); 31 } 32 33 @After 34 public void tearDown() { 35 SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); 36 Session s = holder.getSession(); 37 s.flush(); 38 TransactionSynchronizationManager.unbindResource(sessionFactory); 39 } 40 @Test 41 public void testInitByXml() { 42 initService.initEntityByXml("orgs.xml"); 43 } 44 }
解析xml文件 将信息保存到数据库;
1 package org.konghao.sys.org.service.impl; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.List; 6 7 import javax.inject.Inject; 8 9 import org.apache.commons.beanutils.BeanUtils; 10 import org.dom4j.Attribute; 11 import org.dom4j.Document; 12 import org.dom4j.DocumentException; 13 import org.dom4j.Element; 14 import org.dom4j.io.SAXReader; 15 import org.konghao.sys.org.iservice.IInitService; 16 import org.konghao.sys.org.model.SysException; 17 import org.springframework.beans.factory.BeanFactory; 18 import org.springframework.stereotype.Service; 19 20 @Service("initService") 21 public class InitService extends AbstractBaseSevice implements IInitService{ 22 23 private Document document; 24 @Inject 25 private BeanFactory factory; 26 27 @Override 28 public void initEntityByXml(String filename) { 29 Element root = this.readDocument(filename); 30 String pname = root.attributeValue("package"); 31 List<Element> initEntitys = root.selectNodes("/entitys/initEntity"); 32 for (Element element : initEntitys) { 33 //如果这个实体存在就不添加 34 if (element.attributeValue("exist") == "1") { 35 continue; 36 }else{ 37 String cname = element.attributeValue("class"); 38 cname = pname + "." + cname; 39 String method = element.attributeValue("method"); 40 List<Element> entitys = (List<Element>)element.selectNodes("entity"); 41 addElements(cname,method,entitys); 42 } 43 } 44 } 45 46 private Element readDocument(String filename){ 47 try { 48 SAXReader saxReader = new SAXReader(); 49 Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename)); 50 return d.getRootElement(); 51 } catch (DocumentException e) { 52 e.printStackTrace(); 53 } 54 return null; 55 56 } 57 58 private void addElements(String cname, String method, List<Element> entitys) { 59 for (Element element : entitys) { 60 addElement(cname , method , element); 61 } 62 } 63 64 private void addElement(String cname, String method, Element element) { 65 List<Attribute> attrs = element.attributes(); 66 try { 67 Object o = Class.forName(cname).newInstance(); 68 String[] methods = method.split("\\."); 69 if (methods.length !=2) { 70 throw new SysException("方法格式不正确"); 71 } 72 String sname = methods[0]; //对应org.xml文件的method的第一个 73 String mname = methods[1]; 74 for (Attribute attribute : attrs) { 75 System.out.println(attribute.getName() + " ; " + attribute.getValue()); 76 String name = attribute.getName(); 77 String value = attribute.getValue(); 78 BeanUtils.copyProperty(o, name, value);//利用反射进行拷贝 79 } 80 Object service = factory.getBean(sname);//该sname应该与注入的service名称一致 ,例如本地中使用的是OrgtypeService,则对应的service也是OrgTypeService,否则将报找不到该注入的类型 81 Method m = service.getClass().getMethod(mname , o.getClass()); 82 m.invoke(service, o); 83 } catch (ClassNotFoundException e) { 84 e.printStackTrace(); 85 } catch (IllegalAccessException e) { 86 e.printStackTrace(); 87 } catch (InvocationTargetException e) { 88 e.printStackTrace(); 89 } catch (SecurityException e) { 90 e.printStackTrace(); 91 } catch (NoSuchMethodException e) { 92 e.printStackTrace(); 93 } catch (InstantiationException e) { 94 e.printStackTrace(); 95 } 96 } 97 98 99
解析文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <entitys package="org.konghao.sys.org.model" > 3 <initEntity exist="1" class="OrgType" method="OrgTypeService.add"> 4 <entity name="学校" sn="XX" /> 5 <entity name="分校" sn="FX" /> 6 <entity name="校办领导" sn="XBLD" /> 7 <entity name="行政部门" sn="XZBM" /> 8 <entity name="教学部门" sn="JXBM" /> 9 <entity name="专业" sn="ZY" /> 10 <entity name="班级" sn=" BJ" /> 11 </initEntity> 12 13 <initEntity exist="0" class="Position" method="PositionService.add"> 14 <entity name="校长" sn="XZ" /> 15 <entity name="副校长" sn="FXZ" /> 16 <entity name="处长" sn="CZ" /> 17 <entity name="副处长" sn="FCZ" /> 18 <entity name="科长" sn="KZ" /> 19 <entity name="辅导员" sn="RDY" /> 20 <entity name="班主任" sn="BZR" /> 21 </initEntity> 22 </entitys>
底层实现:
1 package org.konghao.sys.org.service.impl; 2 3 import java.util.List; 4 5 import javax.inject.Inject; 6 7 import org.konghao.sys.org.idao.IOrgTypeDao; 8 import org.konghao.sys.org.iservice.IOrgTypeService; 9 import org.konghao.sys.org.model.OrgType; 10 import org.konghao.sys.org.model.SysException; 11 import org.springframework.stereotype.Service; 12 13 @Service("OrgTypeService") 14 public class OrgTypeService extends AbstractBaseSevice implements IOrgTypeService{ 15 16 @Inject 17 private IOrgTypeDao orgTypeDao; 18 19 @Override 20 public void add(OrgType orgType) { 21 if (orgTypeDao.loadBySn(orgType.getSn()) != null) { 22 throw new SysException("要添加的组织机构类型的sn已经存在"); 23 } 24 orgTypeDao.add(orgType); 25 } 26 27 28 }
spring的beans.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.0.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 12 http://www.springframework.org/schema/tx 13 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 14 <!-- 打开Spring的Annotation支持 --> 15 <context:annotation-config /> 16 <!-- 设定Spring 去哪些包中找Annotation --> 17 <context:component-scan base-package="org.konghao" /> 18 19 <bean id="ftlPath" class="java.lang.String"> 20 <constructor-arg value="/ftl"/> 21 </bean> 22 23 <bean id="outPath" class="java.lang.String"> 24 <constructor-arg value="/jsp/template"/> 25 </bean> 26 27 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 28 destroy-method="close"> 29 <property name="driverClassName" value="${jdbc.driverClassName}" /> 30 <property name="url" value="${jdbc.url}" /> 31 <property name="username" value="${jdbc.username}" /> 32 <property name="password" value="${jdbc.password}" /> 33 <!-- 配置连接池的初始值 --> 34 <property name="initialSize" value="1" /> 35 <!-- 连接池的最大值 --> 36 <!-- <property name="maxActive" value="500"/> --> 37 <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 --> 38 <!-- <property name="maxIdle" value="2"/> --> 39 <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 --> 40 <property name="minIdle" value="1" /> 41 <property name="maxActive" value="100" /> 42 <property name="maxIdle" value="20" /> 43 <property name="maxWait" value="1000" /> 44 </bean> 45 <!--创建Spring的SessionFactory工厂 --> 46 <context:property-placeholder location="classpath:jdbc.properties" /> 47 <!-- 48 和hibernate4整合没有提供专门的针对Annotation的类,直接在LocalSessionFactoryBean中已经集成 49 --> 50 <bean id="sessionFactory" 51 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 52 <!-- 注入数据源 --> 53 <property name="dataSource" ref="dataSource" /> 54 <!-- 设置Spring取那个包中查找相应的实体类 --> 55 <property name="packagesToScan"> 56 <value>org.konghao.sys.org.model</value> 57 </property> 58 <property name="hibernateProperties"> 59 <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> 60 <props> 61 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 62 <prop key="hibernate.show_sql">true</prop> 63 <prop key="hibernate.hbm2ddl.auto">update</prop> 64 <prop key="hibernate.format_sql">true</prop> 65 </props> 66 </property> 67 </bean> 68 69 <!-- 配置Spring的事务处理 --> 70 <!-- 创建事务管理器--> 71 <bean id="txManager" 72 class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 73 <property name="sessionFactory" ref="sessionFactory" /> 74 </bean> 75 <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> 76 <aop:config> 77 <!-- 设置pointCut表示哪些方法要加入事务处理 --> 78 <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 79 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> 80 <aop:pointcut id="allMethods" 81 expression="execution(* org.konghao.sys.org.service.impl.*.*(..))" /> 82 <!-- 通过advisor来确定具体要加入事务控制的方法 --> 83 <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> 84 </aop:config> 85 <!-- 配置哪些方法要加入事务控制 --> 86 <tx:advice id="txAdvice" transaction-manager="txManager"> 87 <tx:attributes> 88 <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> 89 <tx:method name="*" propagation="REQUIRED" read-only="true"/> 90 <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> 91 <tx:method name="add*" propagation="REQUIRED"/> 92 <tx:method name="del*" propagation="REQUIRED"/> 93 <tx:method name="update*" propagation="REQUIRED"/> 94 <tx:method name="save*" propagation="REQUIRED"/> 95 <tx:method name="clear*" propagation="REQUIRED"/> 96 <tx:method name="empty*" propagation="REQUIRED"/> 97 <tx:method name="init*" propagation="REQUIRED"/> 98 </tx:attributes> 99 </tx:advice> 100 </beans>
————————————————————————————————————————————————————————————————————————
版本3: 多层次解析xml文件的实现
1 package org.konghao.sys.org.service.impl; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import javax.inject.Inject; 9 import javax.persistence.criteria.CriteriaBuilder.In; 10 11 import org.apache.commons.beanutils.BeanUtils; 12 import org.dom4j.Attribute; 13 import org.dom4j.Document; 14 import org.dom4j.DocumentException; 15 import org.dom4j.Element; 16 import org.dom4j.io.SAXReader; 17 import org.konghao.sys.org.iservice.IInitService; 18 import org.konghao.sys.org.model.OrgType; 19 import org.konghao.sys.org.model.SysException; 20 import org.springframework.beans.factory.BeanFactory; 21 import org.springframework.stereotype.Service; 22 23 @Service("initService") 24 public class InitService extends AbstractBaseSevice implements IInitService{ 25 26 private Document document; 27 @Inject 28 private BeanFactory factory; 29 30 @Override 31 public void initEntityByXml(String filename) { 32 Element root = this.readDocument(filename); 33 String pname = root.attributeValue("package"); 34 List<Element> initEntitys = root.selectNodes("/entitys/initEntity"); 35 for (Element element : initEntitys) { 36 String ipname = element.attributeValue("package"); 37 String cname = element.attributeValue("class"); 38 System.out.println(element.attributeValue("exist")); 39 //如果为1 表示已经添加过了 40 if (element.attributeValue("exist") == "1" || element.attributeValue("exist").equals("1")) { 41 continue; 42 }if (ipname != null && !"".equals(ipname)) { 43 cname = ipname + "." + cname; 44 } else{ 45 cname = pname + "." + cname; 46 } 47 String method = element.attributeValue("method"); 48 List<Element> entitys = (List<Element>)element.selectNodes("entity"); 49 System.out.println(cname + " " + method ); 50 addElements(cname,method,entitys); 51 52 } 53 } 54 55 private Element readDocument(String filename){ 56 try { 57 SAXReader saxReader = new SAXReader(); 58 Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename)); 59 return d.getRootElement(); 60 } catch (DocumentException e) { 61 e.printStackTrace(); 62 } 63 return null; 64 65 } 66 67 private void addElements(String cname, String method, List<Element> entitys) { 68 for (Element element : entitys) { 69 addElement(cname , method , element , null); 70 } 71 } 72 73 private void addElement(String cname, String method, Element e,Object parent) { 74 try { 75 //获取所有的属性 76 List<Attribute> atts = (List<Attribute>)e.attributes(); 77 Object obj = Class.forName(cname).newInstance(); 78 String [] ms = method.split("\\."); 79 if(ms.length!=2) throw new SysException("方法格式不正确"); 80 String sname = ms[0]; String mname = ms[1]; 81 for(Attribute att:atts) { 82 String name = att.getName(); 83 String value = att.getValue(); 84 BeanUtils.copyProperty(obj, name, value); 85 } 86 if(parent!=null) { 87 BeanUtils.copyProperty(obj, "parent", parent); 88 } 89 Object service = factory.getBean(sname); 90 Method m = service.getClass().getMethod(mname,obj.getClass()); 91 m.invoke(service, obj); 92 List<Element> es = e.selectNodes("entity"); 93 for(Element ele:es) { 94 addElement(cname, method, ele, obj); 95 } 96 } catch (ClassNotFoundException e1) { 97 e1.printStackTrace(); 98 } catch (IllegalAccessException e1) { 99 e1.printStackTrace(); 100 } catch (InvocationTargetException e1) { 101 e1.printStackTrace(); 102 } catch (SecurityException e1) { 103 e1.printStackTrace(); 104 } catch (NoSuchMethodException e1) { 105 e1.printStackTrace(); 106 } catch (InstantiationException e1) { 107 e1.printStackTrace(); 108 } 109 } 110 111 }
实体类Org
1 package org.konghao.sys.org.model; 2 3 import java.util.List; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.JoinColumn; 10 import javax.persistence.ManyToOne; 11 import javax.persistence.Table; 12 13 /** 14 * 组织对象,该表可以生成完整的组织树 15 * 根据组织类型来具体存储实际中存在的组织 16 * 学院 --> xx 17 * 校本部--> FX 18 * 南校区--> FX 19 * @author jrx 20 * 21 */ 22 @Entity 23 @Table(name="t_org") 24 public class Org { 25 26 /** 27 * 组织机构的id 28 */ 29 private int id; 30 /** 31 * 组织机构的名称 32 */ 33 private String name ; 34 /** 35 * 组织机构所属类型的id,此处不要使用ManyToOne 36 */ 37 private Integer typeId; 38 /** 39 * 组织机构所属类型的名称,冗余 40 */ 41 private String typeName; 42 /** 43 * 组织机构的排序号 44 */ 45 private Integer orderNum ; 46 /** 47 * 组织机构的父亲组织 48 */ 49 private Org parent ; 50 /** 51 * 管理类型 52 */ 53 private int managerType; 54 /** 55 * 组织机构的地址 56 */ 57 private String address ; 58 /** 59 * 组织机构的电话 60 */ 61 private String phone ; 62 /** 63 * 扩展属性,用于在针对某些特殊的组织存储相应的信息 64 */ 65 private String att1 ; 66 private String att2 ; 67 private String att3 ; 68 69 @Id 70 @GeneratedValue 71 public int getId() { 72 return id; 73 } 74 75 public void setId(int id) { 76 this.id = id; 77 } 78 79 public String getName() { 80 return name; 81 } 82 83 public void setName(String name) { 84 this.name = name; 85 } 86 87 @Column(name="tid") 88 public Integer getTypeId() { 89 return typeId; 90 } 91 92 public void setTypeId(Integer typeId) { 93 this.typeId = typeId; 94 } 95 @Column(name="tname") 96 public String getTypeName() { 97 return typeName; 98 } 99 100 public void setTypeName(String typeName) { 101 this.typeName = typeName; 102 } 103 @Column(name="order_num") 104 public Integer getOrderNum() { 105 return orderNum; 106 } 107 108 public void setOrderNum(Integer orderNum) { 109 this.orderNum = orderNum; 110 } 111 @ManyToOne 112 @JoinColumn(name="pid") 113 public Org getParent() { 114 return parent; 115 } 116 117 public void setParent(Org parent) { 118 this.parent = parent; 119 } 120 121 public String getAddress() { 122 return address; 123 } 124 125 public void setAddress(String address) { 126 this.address = address; 127 } 128 129 public String getPhone() { 130 return phone; 131 } 132 133 public void setPhone(String phone) { 134 this.phone = phone; 135 } 136 137 public String getAtt1() { 138 return att1; 139 } 140 141 public void setAtt1(String att1) { 142 this.att1 = att1; 143 } 144 145 public String getAtt2() { 146 return att2; 147 } 148 149 public void setAtt2(String att2) { 150 this.att2 = att2; 151 } 152 153 public String getAtt3() { 154 return att3; 155 } 156 157 public void setAtt3(String att3) { 158 this.att3 = att3; 159 } 160 161 @Column(name = "manager_type") 162 public int getManagerType() { 163 return managerType; 164 } 165 166 public void setManagerType(int managerType) { 167 this.managerType = managerType; 168 } 169 170 @Override 171 public String toString() { 172 return "Org [id=" + id + ", name=" + name + ", typeId=" + typeId 173 + ", typeName=" + typeName + ", orderNum=" + orderNum 174 + ", parent=" + parent + ", managerType=" + managerType 175 + ", address=" + address + ", phone=" + phone + ", att1=" 176 + att1 + ", att2=" + att2 + ", att3=" + att3 + "]"; 177 } 178 179 180 }
底层实现:
1 package org.konghao.sys.org.service.impl; 2 3 import java.util.List; 4 5 import javax.inject.Inject; 6 7 import org.konghao.basic.model.Pager; 8 import org.konghao.sys.dto.TreeDto; 9 import org.konghao.sys.org.idao.IOrgDao; 10 import org.konghao.sys.org.idao.IOrgTypeDao; 11 import org.konghao.sys.org.iservice.IOrgService; 12 import org.konghao.sys.org.model.Org; 13 import org.konghao.sys.org.model.SysException; 14 import org.springframework.stereotype.Service; 15 16 @Service("orgService") 17 public class OrgService extends AbstractBaseSevice implements IOrgService { 18 19 20 @Inject 21 private IOrgDao orgDao; 22 23 @Inject 24 private IOrgTypeDao orgTypeDao; 25 26 private void checkChildOrgNum(Org cOrg , Org pOrg){ 27 if (pOrg == null) { 28 return; 29 } 30 //获取根据组织类型获取某组织类型下组织的数量(数量根据OrgTypeRule的num来确定数量,即某类型下组织数量需小于等于OrgTypeRule中num的数量) 31 int hnum = orgDao.loadNumByType(pOrg.getId(), cOrg.getTypeId()); 32 //根据组织类型的父id和子id获取num数量 33 int rnum = orgTypeDao.loadOrgTypeRuleNum(pOrg.getTypeId(), cOrg.getTypeId()); 34 if (rnum < 0) { 35 return; 36 } 37 if (hnum >= rnum) { 38 throw new SysException(pOrg.getName() +"下的" + cOrg.getName() + "的数量已经达到最大化"); 39 } 40 } 41 42 //parent已经存在的添加 43 @Override 44 public void add(Org org) { 45 checkChildOrgNum(org, org.getParent()); 46 if (org.getParent() != null) { 47 org.setOrderNum(orgDao.getMaxOrder(org.getParent().getId())); 48 }else { 49 org.setOrderNum(null); 50 } 51 orgDao.add(org); 52 } 53 54 @Override 55 public void add(Org org, Integer pid) { 56 if (pid != null) { 57 Org p = orgDao.load(pid); 58 if (p == null) { 59 throw new SysException("要添加的父组织不存在"); 60 } 61 checkChildOrgNum(org, org.getParent()); 62 org.setParent(p); 63 } 64 org.setOrderNum(orgDao.getMaxOrder(pid)); 65 orgDao.add(org); 66 } 67 68 }