参考;链接
问题:很奇怪的是,为什么IUserDao没有实现其接口,也没有在IUserDao
@Service("userService") public class UserServiceImpl implements IUserService{ @Resource(name="IUserDao")//这里可以是@Resource,因为默认就是类或接口的名字
public IUserDao userDao;
public User getUserById(int userId) {
// TODO Auto-generated method stub
return this.userDao.selectByPrimaryKey(userId);
}
}
public interface IUserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
原因分析:其实这是由于在mybatis.xml里面配置了下面的bean,在mapping.xml里面定义了相应的操作,crud,这里会与dao接口中的方法名进行匹配,
相当于此处实例化了dao里面的IUserDao接口,然后交给了Spring来管理,自然就可以从Spring中拿到实例化后的对象。
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cn.hnust.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean>
这里有对org.mybatis.spring.mapper.MapperScannerConfigurer进行解释 http://www.2cto.com/kf/201409/331321.html