使用MapperScannerConfigurer簡化MyBatis配置

來源:互聯網
上載者:User

標籤:err   nbsp   tno   dmi   sql   test   ann   cto   void   

MyBatis的一大亮點就是可以不用DAO的實作類別。

如果沒有實作類別,Spring如何為Service注入DAO的執行個體呢?MyBatis-Spring提供了一個MapperFactoryBean,可以將資料對應介面轉為Spring Bean。

<div>
<beans>   <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">     <property name="mapperInterface" value="dao.UserMapper"/>     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>     </bean>   </beans></div>

如果資料對應介面很多的話,需要在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配置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.