標籤:sse val pojo tno 掃描 介面 configure 指定 ext
MyBatis的一大亮點就是可以不用DAO的實作類別。如果沒有實作類別,Spring如何為Service注入DAO的執行個體呢?MyBatis-Spring提供了一個MapperFactoryBean,可以將資料對應介面轉為Spring Bean。
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="dao.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
如果資料對應介面很多的話,需要在Spring的設定檔中對資料對應介面做配置,相應的配置項會很多了。為了簡化配置,在MyBatis-Spring中提供了一個轉換器MapperScannerConfig它可以將介面轉換為Spring容器中的Bean,在Service中@Autowired的方法直接注入介面執行個體。在Spring的設定檔中可以採用以下所示的配置將介面轉化為Bean。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="basePackage" value="dao"/> </bean> <context:component-scan base-package="service"/>
MapperScannerConfigurer將掃描basePackage所指定的包下的所有介面類(包括子類),如果它們在SQL對應檔中定義過,則將它們動態定義為一個Spring Bean,這樣,我們在Service中就可以直接注入映射介面的bean,service中的代碼如下
package service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dao.UserMapper; import pojo.User; import service.UserService; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUser(User user) { return userMapper.getUser(user); } }
接下來,建立測試類別進行測試
package test; import junit.framework.Assert; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.User; import service.UserService; public class TestService { @Test public void test(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService=(UserService)context.getBean("userService"); User user=new User(); user.setUsername("admin"); user.setPassword("admin"); User u=userService.getUser(user); Assert.assertNotNull(u); } }
使用MapperScannerConfigurer簡化MyBatis配置