簡介
Spring+SpringMVC+MyBatis框架(SSM)是比較熱門的中小型企業級項目開發的框架,對於新手來說也是比較容易學習入門的。雖說容易,但在框架搭建過程中仍然遇到了許多問題,因此用實例記錄下來吧。
實例
第一步——導包
Spring框架包及其依賴包
MyBatis框架包及其依賴包
MyBatis-EhCache架包
C3P0架包
MySql數據庫驅動包
項目架包如下:
項目結構如下:
第二步——整合Dao層(Spring+MyBatis)
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
因為MyBatis交給Spring管理,因此Mapper在Spring中配置,這里的配置只打開二級緩存
applicationContext-dao.xml
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db_pwc" />
<property name="user" value="pwc" />
<property name="password" value="123456" />
<property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="1" />
<property name="initialPoolSize" value="3" />
<property name="maxIdleTime" value="15" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.pwc.dao.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
1.該配置自動掃描單例化采用代理方式的Mapper,單例化的Mapper的bean名為Mapper接口第一個字母為小寫的名。
2.千萬要注意sqlSessionFactory的bean中的configLocation屬性,其value值務必記得加上classpath:前綴,不然無法加載MyBatis配置文件
第二步——整合Service層(Spring)
業務接口和業務實現
UserService.java
package cn.pwc.service;
import java.util.List;
import cn.pwc.pojo.User;
public interface UserService {
public void add(User user) throws Exception;
public void delete(User user) throws Exception;
public User getUserById(int id) throws Exception;
public List<User> listUserByAge(int age) throws Exception;
}
UserServiceBean.java
package cn.pwc.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.pwc.dao.mapper.UserMapper;
import cn.pwc.pojo.User;
import cn.pwc.service.UserService;
@Service @Transactional
public class UserServiceBean implements UserService{
@Resource(name="userMapper")
private UserMapper mapper;
@Override
public void add(User user) throws Exception {
mapper.insert(user);
}
@Override
public void delete(User user) throws Exception {
mapper.deleteById(user.getId());
}
@Override
public User getUserById(int id) throws Exception {
User user=null;
user=mapper.findById(id);
if(user==null){
throw new Exception("User is not existed!");
}
return user;
}
@Override
public List<User> listUserByAge(int age) throws Exception {
List<User> list=null;
list=mapper.findByAge(age);
if(list==null){
throw new Exception("List is empty!");
}
return list;
}
}
本實例采用自動掃描加載的方式,因此該業務bean需注解@Service
本實例交由Spring管理事務,因此該業務bean需注解@Transactional
applicationContext-service.xml
<context:component-scan base-package="cn.pwc.service" />
第三步——添加事務管理
applicationContext-transaction.xml
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
第四步——整合視圖層(SpringMVC)
springmvc.xml
<context:component-scan base-package="cn.pwc.controller"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
采用mvc:annotation-driven標簽自動裝載視圖控制器處理器解析器等
視圖Controller(HelloController.java)
package cn.pwc.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.pwc.pojo.User;
import cn.pwc.service.UserService;
@Controller
public class HelloController {
@Resource(name="userServiceBean")
private UserService service;
@RequestMapping("/hello")
public ModelAndView sayHello(){
User user=null;
User user2=null;
User user3=null;
try {
user = service.getUserById(1);
user2=service.getUserById(1);
user3=service.getUserById(1);
System.out.println("OK!");
} catch (Exception e) {
e.printStackTrace();
}
ModelAndView view=new ModelAndView("hello");
view.addObject("user", user);
return view;
}
}
該Controller類需注解@Controller
視圖控制方法需注解@RequestMapping,作為url請求處理方法
第五步——將所有配置裝載到Spring容器中
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
務必注意servlet-mapping中url-pattern屬性值不能為/*
加載的配置文件路徑必須有classpath:前綴
測試
版權聲明:本文為博主原創文章,未經博主允許不得轉載。