One of the highlights of MyBatis is that you can use the DAO implementation class. If there is no implementation class, how does spring inject an instance of DAO for service? Mybatis-spring provides a mapperfactorybean that can convert the data-mapping interface into a spring Bean.
<bean id= " userdao " class = " org.mybatis.spring.mapper.mapperfactorybean " > <property name= " mapperinterface " Span style= "COLOR: #800000" > " value=" dao. Usermapper "/> <property name=" sqlsessionfactory " ref =" sqlsessionfactory "/> </bean> </beans>
If you have a lot of data-mapping interfaces, you need to configure the data-mapping interface in spring's configuration file, and the corresponding configuration items will be many. To simplify the configuration, a translator is provided in mybatis-spring mapperscannerconfig it can convert the interface into a bean in the spring container and inject the interface instance directly into the service @autowired method. In the spring configuration file, the interface can be converted to beans using the configuration shown below.
<beanclass="Org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlsessionfactory" ref="sqlsessionfactory"/> <property name="Basepackage"Value="DAO"/> </bean> <context:component-scanBase-package="Service"/>
Mapperscannerconfigurer will scan all interface classes (including subclasses) under the package specified by Basepackage, and if they are defined in the SQL mapping file, dynamically define them as a spring Bean, so that The code in Bean,service that we can inject directly into the map interface in the service is as follows
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") publicclass Userserviceimpl implements UserService { @Autowired private usermapper usermapper; @Override public user getUser (user user) { return Usermapper.getuser (user); } }
Next, create a test class to test
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 classTestservice {@Test Public voidTest () {ApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); UserService UserService= (UserService) Context.getbean ("UserService"); User User=NewUser (); User.setusername ("Admin"); User.setpassword ("Admin"); User u=userservice.getuser (user); Assert.assertnotnull (U); } }
Simplifying MyBatis configuration with Mapperscannerconfigurer