Injecting Mappers
DAO除了手动使用SqlSessionDaoSupport或是SqlSessionTemplate之外,Mybatis-Spring提供了另外一种方法,使用代理工厂—MapperFactoryBean。它允许你直接将map接口注入到Service beans中去,而不用编写实现类(DAOImpl)。因为Mybatis-Spring会为你创建代理。
将mapper加入Spring的配置方法:
- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
- <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean>
- <bean id="fooService" class="org.mybatis.spring.sample.mapper.FooServiceImpl">
- <property name="userMapper" ref="userMapper" />
- </bean>
- public class FooServiceImpl implements FooService {
- private UserMapper userMapper;
- public void setUserMapper(UserMapper userMapper) {
- this.userMapper = userMapper;
- }
- public User doSomeBusinessStuff(String userId) {
- return this.userMapper.getUser(userId);
- }
- }
本文介绍如何使用MyBatis-Spring的MapperFactoryBean来注入Mapper接口,从而避免手动编写DAO实现。通过示例展示了如何配置MapperFactoryBean以及如何在Service中注入和使用Mapper。




被折叠的 条评论
为什么被折叠?



