进行一个测试,要养成每做完一个小模块必须测试的习惯。步步为营,如果整个项目配置完了然后在进行测试,那么有问题进行排除会变得很困难。
package com.ys.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ys.mapper.UserMapper;
import com.ys.po.User;
public class DaoTest {
ApplicationContext context = null;
@Before
public void init(){
context = new ClassPathXmlApplicationContext("classpath:spring/application-dao.xml");
}
@Test
public void testSelectByPrimaryKey(){
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user.getPassword());
}
}
这里是根据 user 表的 id 进行查询。如果能打印出user对象的值,那么前面的配置是 OK的。
4、整合 service
前面我们整理了,这层就是用 Spring 来管理 service 接口,我们会使用 xml 配置的方式来将 service 接口配置到 spring 配置文件中。而且事务控制也是在 service 层进行配置。
这里我们以登录
①、定义 service 接口
package com.ys.service.impl;
import com.ys.po.User;
public interface IUserService {
//通过用户名和密码查询User
public User selectUserByUsernameAndPassword(User user);
}
②、编写 service 实现类
package com.ys.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.ys.mapper.UserMapper;
import com.ys.po.User;
import com.ys.service.impl.IUserService;
public class UserServiceImpl implements IUserService{
@Autowired
private UserMapper userMapper; //通过@Autowired向spring容器注入UserMapper
//通过用户名和密码查询User
@Override
public User selectUserByUsernameAndPassword(User user) {
User u = userMapper.selectUserByUsernameAndPassword(user);
return u;
}
}
通过@Autowired向spring容器注入UserMapper,它会通过spring配的扫描器扫描到,并将对象装载到spring容器中。
③、在spring容器中配置 Service 接口,这里我们使用 xml 的方式
在 config/spring 目录下,新建 spring-service.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:mvc="http://www.springframework.org/schema/mvc"
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://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!--配置UserServiceImpl -->
<bean id="userService" class="com.ys.service.UserServiceImpl"></bean>
</beans>
④、在spring容器中配置 事务处理
在 config/spr