後端-框架-Spring-MyBatis-注入對映器
阿新 • • 發佈:2018-11-11
後端-框架-Spring-MyBatis-注入對映器
其中的配置檔案
<!-- 資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true& characterEncoding=utf-8&useSSL=true"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- Dao -->
<!-- 對於MapperFactoryBean有什麼屬性,F3 -->
<!-- 通過Spring直接建立userMapper bean,不用手動實現 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.smbms.dao.user.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!-- Service -->
<!-- 掃描註解定義 -->
<context:component-scan base-package="cn.smbms.service"></context:component-scan>
其中的配置檔案(偷懶)
<!-- 資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=true"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- Dao -->
<!-- 通過MapperScannerConfigurer掃描基準包下的對映檔案 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.smbms.dao"></property>
</bean>
<!-- Service -->
<!-- 掃描註解定義 -->
<!-- 通過註釋類,實現自動注入bean -->
<context:component-scan base-package="cn.smbms.service"></context:component-scan>
註釋類
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userMapper")
private UserMapper userMapper;
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> findUsers(User user) {
// TODO Auto-generated method stub
return userMapper.getUserList(user);
}
}