0%

Spring和Mybatis的整合-续

接上回Spring和Mybatis的整合。上回只是将mapper.xml文件在applicationContext.xml里头配置,这样的话就得每个mapper都配置一遍,文件多了就会比较不好管理。所以想着用Spring的自动扫描包,来扫描mapper并自动生成bean。

修改applicationContext.xml

加入自动扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 用这种方法配置mapper和dao就不用在同一目录下 -->

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

创建接口dao的实现类

并加上@Component的注解,即可让自动扫描识别

1
2
3
4
5
6
7
8
9
10
11
@Component
public class StoreMybatisDaoImpl implements StoreMybatisDao {
@Resource
private StoreMybatisDao storeDao;
@Override
public Store getStore(int id) {
// TODO Auto-generated method stub
return this.storeDao.getStore(id);
}

}

不过其实不实现接口也可以出结果,只要在dao接口类上加@Component注解

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class test {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx=null;
ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
StoreMybatisDao storeDao=(StoreMybatisDao) ctx.getBean("storeMybatisDao");
Store store=new Store();

store = storeDao.getStore(9);
System.out.println(store.getName().toString());

}

}

原来的测试类改一下bean ID就可以,自动生成的bean ID是类名首字母小写,曾经被这个困扰很久
据说注解@Component(“xxx”)这样写可以显式地指定bean id,不过实测无效,不知是不是我自己的问题,可能是版本的错吧
(或者是时辰的错啊【雾】(其实错的不是我,是世界【大雾】

Spring MVC

做到这里,只要再引入SpringMVC的配置文件,以及修改web.xml,大概就是个最基本的ssm框架了,然后就可以用这个框架为所欲为了蛤蛤