spring测试类test测试⽅法
实例掩码地址为:
1 <!-- Spring 的可以通过这个上下⽂参数来获取l的位置 -->
2 <context-param>
3 <param-name>contextConfigLocation</param-name>
4 <param-value>classpath*:l</param-value>
5 </context-param>
测试类
1package org.konghao.service;
2
3import javax.inject.Inject;
4
5import org.hibernate.Session;
6import org.hibernate.SessionFactory;
7import org.junit.After;
8import org.junit.Before;
9import org.junit.Test;
10import org.junit.runner.RunWith;
11import org.iservice.IInitService;
12import hibernate4.SessionHolder;
13import st.context.ContextConfiguration;
14import st.context.junit4.SpringJUnit4ClassRunner;
15import ansaction.support.TransactionSynchronizationManager;
16
17 @RunWith(SpringJUnit4ClassRunner.class)
18 @ContextConfiguration("/l")
19public class TestInitService {
20 @Inject
21private 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) Resource(sessionFactory);
36 Session s = Session();
37 s.flush();
38 TransactionSynchronizationManager.unbindResource(sessionFactory);
39 }
40 @Test
41public void testInitByXml() {
42 initService.initEntityByXml("l");
43 }
44 }
解析xml⽂件将信息保存到数据库;
1package org.service.impl;
2
3import flect.InvocationTargetException;
4import flect.Method;
5import java.util.List;
6
7import javax.inject.Inject;
8
9import org.apachemons.beanutils.BeanUtils;
10import org.dom4j.Attribute;
11import org.dom4j.Document;
12import org.dom4j.DocumentException;
13import org.dom4j.Element;
14import org.dom4j.io.SAXReader;
15import org.iservice.IInitService;
16import org.del.SysException;
17import org.springframework.beans.factory.BeanFactory;
18import org.springframework.stereotype.Service;
19
20 @Service("initService")
21public class InitService extends AbstractBaseSevice implements IInitService{
22
23private Document document;
24 @Inject
25private BeanFactory factory;
26
27 @Override
28public void initEntityByXml(String filename) {
29 Element root = adDocument(filename);
30 String pname = root.attributeValue("package");
31 List<Element> initEntitys = root.selectNodes("/entitys/initEntity");
32for (Element element : initEntitys) {
33//如果这个实体存在就不添加
34if (element.attributeValue("exist") == "1") {
35continue;
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
46private Element readDocument(String filename){
47try {
48 SAXReader saxReader = new SAXReader();
49 Document d = ad( ClassLoader().getResourceAsStream("init/" + filename));
RootElement();
51 } catch (DocumentException e) {
52 e.printStackTrace();
53 }
54return null;
55
56 }
57
58private void addElements(String cname, String method, List<Element> entitys) {
59for (Element element : entitys) {
60 addElement(cname , method , element);
61 }
62 }
63
64private void addElement(String cname, String method, Element element) {
65 List<Attribute> attrs = element.attributes();
66try {
67 Object o = Class.forName(cname).newInstance();
68 String[] methods = method.split("\\.");
69if (methods.length !=2) {
70throw new SysException("⽅法格式不正确");
71 }
72 String sname = methods[0]; //对应l⽂件的method的第⼀个
73 String mname = methods[1];
74for (Attribute attribute : attrs) {
75 System.out.Name() + " ; " + Value());
76 String name = Name();
77 String value = Value();
78 pyProperty(o, name, value);//利⽤反射进⾏拷贝
79 }
80 Object service = Bean(sname);//该sname应该与注⼊的service名称⼀致,例如本地中使⽤的是OrgtypeService,则对应的service也是OrgTypeService,否则将报不到该注⼊的类型
81 Method m = Class().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.del" >
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>
底层实现:
1package org.service.impl;
2
3import java.util.List;
4
5import javax.inject.Inject;
6
7import org.idao.IOrgTypeDao;
8import org.iservice.IOrgTypeService;
9import org.del.OrgType;
10import org.del.SysException;
11import org.springframework.stereotype.Service;
12
13 @Service("OrgTypeService")
14public class OrgTypeService extends AbstractBaseSevice implements IOrgTypeService{
15
16 @Inject
17private IOrgTypeDao orgTypeDao;
18
19 @Override
20public void add(OrgType orgType) {
21if (orgTypeDao.Sn()) != null) {
22throw new SysException("要添加的组织机构类型的sn已经存在");
23 }
24 orgTypeDao.add(orgType);
25 }
26
27
28 }
spring的l配置
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="/schema/beans"
3 xmlns:xsi="/2001/XMLSchema-instance" xmlns:aop="/schema/aop"
4 xmlns:context="/schema/context"
5 xmlns:tx="/schema/tx"
6 xsi:schemaLocation="/schema/beans
7 /schema/beans/spring-beans-3.0.xsd
8 /schema/context
9 /schema/context/spring-context-3.0.xsd
10 /schema/aop
11 /schema/aop/spring-aop-3.0.xsd
12 /schema/tx
13 /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.apachemons.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"
51class="hibernate4.LocalSessionFactoryBean">
52 <!-- 注⼊数据源 -->
53 <property name="dataSource" ref="dataSource" />
54 <!-- 设置Spring取那个包中查相应的实体类 -->
55 <property name="packagesToScan">
56 <value>org.del</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"
72class="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.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⽂件的实现
1package org.service.impl;
2
3import flect.InvocationTargetException;
4import flect.Method;
5import java.util.Iterator;
6import java.util.List;
7
8import javax.inject.Inject;
9import iteria.CriteriaBuilder.In;
10
11import org.apachemons.beanutils.BeanUtils;
12import org.dom4j.Attribute;
13import org.dom4j.Document;
14import org.dom4j.DocumentException;
15import org.dom4j.Element;
16import org.dom4j.io.SAXReader;
17import org.iservice.IInitService;
18import org.del.OrgType;
19import org.del.SysException;
20import org.springframework.beans.factory.BeanFactory;
21import org.springframework.stereotype.Service;
22
23 @Service("initService")
24public class InitService extends AbstractBaseSevice implements IInitService{
25
26private Document document;
27 @Inject
28private BeanFactory factory;
29
30 @Override
31public void initEntityByXml(String filename) {
32 Element root = adDocument(filename);
33 String pname = root.attributeValue("package");
34 List<Element> initEntitys = root.selectNodes("/entitys/initEntity");
35for (Element element : initEntitys) {
36 String ipname = element.attributeValue("package");
37 String cname = element.attributeValue("class");
38 System.out.println(element.attributeValue("exist"));
39//如果为1 表⽰已经添加过了
40if (element.attributeValue("exist") == "1" || element.attributeValue("exist").equals("1")) {
41continue;
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
55private Element readDocument(String filename){
56try {
57 SAXReader saxReader = new SAXReader();
58 Document d = ad( ClassLoader().getResourceAsStream("init/" + filename)); RootElement();
60 } catch (DocumentException e) {
61 e.printStackTrace();
62 }
63return null;
64
65 }
66
67private void addElements(String cname, String method, List<Element> entitys) {
68for (Element element : entitys) {
69addElement(cname , method , element , null);
70 }
71 }
72
73private void addElement(String cname, String method, Element e,Object parent) {
74try {
75//获取所有的属性
76 List<Attribute> atts = (List<Attribute>)e.attributes();
77 Object obj = Class.forName(cname).newInstance();
78 String [] ms = method.split("\\.");
79if(ms.length!=2) throw new SysException("⽅法格式不正确");
80 String sname = ms[0]; String mname = ms[1];
81for(Attribute att:atts) {
82 String name = Name();
83 String value = Value();
84 pyProperty(obj, name, value);
85 }
86 if(parent!=null) {
87 pyProperty(obj, "parent", parent);
88 }
89 Object service = Bean(sname);
90 Method m = Class().getMethod(Class());
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
1package org.del;
2
3import java.util.List;
4
5import javax.persistence.Column;
6import javax.persistence.Entity;
7import javax.persistence.GeneratedValue;
8import javax.persistence.Id;
9import javax.persistence.JoinColumn;
10import javax.persistence.ManyToOne;
11import 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")
24public class Org {
25
使用dom4j解析xml文件26/**
27 * 组织机构的id
28*/
29private int id;
30/**
31 * 组织机构的名称
32*/
33private String name ;
34/**
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论