- @Before注解的方法中的代码会在@Test注解的方法中首先被执行。
- @After注解的方法中的代码会在@Test注解的方法中首先被执行。
- 不使用@Before和@After注解:
public class MyTest {
@Test
public void testA() throws IOException {
//使用IO流读取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//取出SqlSession的对象
SqlSession sqlSession = factory.openSession();
//完成查询操作
List<Student> list = sqlSession.selectList("clh.getAll");
list.forEach(student -> System.out.println(student));
//关闭SqlSession对象(还回到数据库连接池)
sqlSession.close();
}
}
- 使用@Before和@After注解:
SqlSession sqlSession;
@Before
public void OpenSqlSession() throws IOException {
//使用IO流读取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//取出SqlSession的对象
SqlSession sqlSession = factory.openSession();
}
@After
public void closeSqlSession(){
//关闭SqlSession对象(还回到数据库连接池)
sqlSession.close();
}
@Test
public void testA() throws IOException {
//完成查询操作
List<Student> list = sqlSession.selectList("clh.getAll");
list.forEach(student -> System.out.println(student));
}
两种代码结果相同,第二种相对简便。