當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring+SpringMVC+Mybatis 整合入门
生活随笔
收集整理的這篇文章主要介紹了
Spring+SpringMVC+Mybatis 整合入门
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 整體結構
- 結構圖
- Spring 整合SpringMVC
- web.xml
- SpringMvc.xml
- Spring整合Mybatis
- applicationContext.xml
- 代理接口的配置accountDaoimpl.xml
- 其余代碼
- 表現層
- 業務層
- 持久層
- domain
- 查詢效果展示
- 附上spring約束
- spring約束
- SpringMVC約束
- Maven 依賴
整體結構
結構圖
Spring 整合SpringMVC
整合SpringMVC我們需要將Spring的配置文件加載到服務器中(配置Spring ioc容器)。
我們可以使用Spring的ContextLoaderListener 監聽器去監聽ServletContext的生命周期。
在啟動服務器時監聽ServletContext的創建,在這時載入Spring的配置文件,這樣就整合成功了。但是有個細節。ContextLoaderListener 默認加載只加載WEB-INF目錄下的的applicationContext.xml文件,所以我們Spring的配置文件的名稱要設置為applicationContext.xml,但是在一般情況下我們的配置文件都會在resouces下面也就是服務器中WEB-INF/classes下面。所以我們需要配置文件路徑:
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param>web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"> <!-- 配置spring的ContextLoaderListener監聽器 --><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>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 加載springmvc配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><!-- 啟動服務器就創建該servlet--><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 解決中文亂碼的過濾器--><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> </web-app>SpringMvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 注解掃描的包 --><context:component-scan base-package="com"><!-- 只掃描的注解--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 過濾的靜態資源--><mvc:resources mapping="/js/" location="/js/**"></mvc:resources><mvc:resources mapping="/css/" location="/css/**"></mvc:resources><mvc:resources mapping="/imgs/" location="/imgs/**"></mvc:resources><!--配置視圖解析器對象--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"><property name="prefix" value="/jsp/"></property><property name="suffix" value=".jsp"></property></bean><!-- 開啟注解驅動 --><mvc:annotation-driven></mvc:annotation-driven> </beans>Spring整合Mybatis
我們將Mybatis的配置集成的Spring的配置文件里。這種方式是最方便的!
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--開啟注解的掃描,只希望掃描service和dao,controller不需要--><context:component-scan base-package="com"><!-- 配置哪些注解不掃描--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- spring 整合Mybatis框架--><!-- 引入外部jdbc配置文件--><context:property-placeholder location="classpath:db.properties"></context:property-placeholder><!-- 配置數據庫連接池--><bean class="org.apache.ibatis.datasource.pooled.PooledDataSource" id="dataSource"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!-- 配置 SqlSessionFactory 工廠--><bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"><!-- 指定數據源 --><property name="dataSource" ref="dataSource"></property><!-- 自動掃描mapping.xml文件,**表示迭代查找 ,,也可在mybatis-config.xml中單獨指定xml文件 --><property name="mapperLocations" value="classpath:mybatis/**/*.xml"></property></bean><!--配置mybatis掃描所在的包--><!-- 自動掃描com/dao下的所有dao接口,并實現這些接口,可直接在程序中使用dao接口,不用再獲取sqlsession對象 --><bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- basePackage 屬性是映射器接口文件的包路徑。你可以使用分號或逗號 作為分隔符設置多于一個的包路徑--><property name="basePackage" value="com.dao"></property></bean><!--Spring 中基于xml的聲明式事務控制配置步驟1、配置事務管理器 DataSourceTransactionManager2、配置事務的通知此時我們需要導入事務的約束 tx名稱空間和約束,同時也需要aop的使用tx:advice 標簽配置事務通知屬性:id:給事務通知起一個唯一標志transaction-manager:給事務通知提供一個事務管理器引用3、配置AOP中的通用切入點表達式4、建立切入點表達式與事務通知的對應關系5、配置事務的屬性是在事務的通知tx:advice 標簽內部配 <tx:attributes>配置事務的屬性isolation:用于指定事務的隔離級別,默認值是DEFAULT,表示使用數據庫的默認隔離級別。propagation:用于指定事務的傳播行為,默認值是REQUIRED,表示一定有事務,增刪改的選擇。查詢方法可以使用SUPPORTSread-only:用于指定事務是否只讀。只有查詢方法才設置為true,默認值為false,表示讀寫。timeout:用于指定事務的超時時間,默認值為-1,表示永不超時。如果設置了指定值,以秒為單位。rollback-for:用于指定一個異常,當產生該異常時,事務回滾,如果產生其他異常,事務不回滾。沒有默認值。表示任何異常都回滾。no-rollback-for:用于指定一個異常,當產生該異常時,事務不回滾,產生其他異常時事務回滾。沒有默認值。表示任何異常都回滾。--><!-- 配置事務管理器--><bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 配置事務的通知--><tx:advice transaction-manager="transactionManager" id="txAdvice"><tx:attributes><tx:method name="find*" read-only="true" propagation="SUPPORTS"/><tx:method name="save*" propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 配置AOP--><aop:config><!-- 配置切入點表達式--><aop:pointcut id="pt1" expression="execution(* com.servcie.impl.*.*(..))"></aop:pointcut><!-- 建立切入點表達式與事務通知的對應關系--><aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor></aop:config> </beans>代理接口的配置accountDaoimpl.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dao.AccountDao"><select id="findAll" resultType="com.domain.Account">select *from account;</select><insert id="saveAccount" parameterType="com.domain.Account">insert into account (name,money) values(#{name},#{money});</insert> </mapper>其余代碼
表現層
package com.controller;import com.domain.Account; import com.servcie.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping;import javax.annotation.Resource; import java.util.List;/*** 賬戶表現層*/ @Controller @RequestMapping("/account") public class AccountController {@Resource(name = "accountService") // @Autowiredprivate AccountService accountService;@RequestMapping("/findAll")public String findAll(Model model) {System.out.println("表現層:查詢所有賬戶");final List<Account> accounts = accountService.findAll(); // System.out.println(accounts);model.addAttribute("accounts", accounts);return "list";}@RequestMapping("saveAccount")public String saveAccount(Account account, Model model) {accountService.saveAccount(account);final List<Account> accounts = accountService.findAll();model.addAttribute("accounts", accounts);return "list";}}業務層
package com.servcie.impl;import com.dao.AccountDao; import com.domain.Account; import com.servcie.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List;@Service("accountService") public class AccountServiceimpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Overridepublic List<Account> findAll() {System.out.println("業務層:查詢所有賬戶信息");final List<Account> all = accountDao.findAll();return all;}@Overridepublic void saveAccount(Account account) {System.out.println("業務層:保存賬戶");accountDao.saveAccount(account);} }持久層
package com.dao;import com.domain.Account; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository;import java.util.List;/*** 賬戶的dao接口*/ @Repository public interface AccountDao {//查詢所有賬戶 // @Select("select *from Account")List<Account> findAll();//保存賬戶 // @Insert("insert into account (name,money) values(#{name},#{money})")void saveAccount(Account account); }domain
package com.domain;import java.io.Serializable;public class Account implements Serializable {private Integer id;private String name;private Double money;@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;} }查詢效果展示
附上spring約束
spring約束
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--開啟注解的掃描,只希望掃描service和dao,controller不需要--><context:component-scan base-package="com"><!-- 配置哪些注解不掃描--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan></beans>SpringMVC約束
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 注解掃描的包 --><context:component-scan base-package="com"><!-- 只掃描的注解--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 開啟注解驅動--><mvc:annotation-driven></mvc:annotation-driven></beans>Maven 依賴
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.5.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.5</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.4</version></dependency><!-- 整合Spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency></dependencies>總結
以上是生活随笔為你收集整理的Spring+SpringMVC+Mybatis 整合入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS 8安装并配置NFS服务
- 下一篇: JupyterHub on Kubern