解决的问题:1.使用Junit进行单元测试时,加载spring配置文件交由junit单独管理。我只管@Test下的方法。
2.junit进行mybatis事务方法我想打印详细信息,通过日志查看事务是否起作用。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:cn/rjx/spring/sm/bean.xml"}) //junit启动时加载配置文件
@Component
public class EmpAction extends AbstractJUnit4SpringContextTests {
@Autowired
EmpService service;
@Test
public void test01(){
Emp emp = service.selectById("1");
System.out.println(emp);
}
@Test
public void test02(){
service.accountChange();
}
}
@Service
public class EmpService{
//org.log4j包
Logger logger=LoggerFactory.getLogger(EmpService.class);
@Autowired
EmpDao empDao;
public Emp selectById(String id){
return empDao.selectById(id);
}
@Transactional()
public void accountChange() {
logger.info("-------add---------");
empDao.addSalary("1");
int a= 10/0;
logger.info("-------update---------");
empDao.updateSalary("2");
}
}
@Repository
public interface EmpDao {
Emp selectById(String id);
void addSalary(String id);
void updateSalary(String id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.rjx.spring.sm.EmpDao">
<select id="selectById" resultType="cn.rjx.spring.sm.Emp">
select * from emp where id=#{id}
</select>
<update id="addSalary">
update emp set salary='6000' where id=#{id}
</update>
<update id="updateSalary">
update emp set salary='4000' where id=#{id}
</update>
</mapper>
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http: