前言html
最近開始嘗試使用久負盛名的SM框架——Spring+Mybatis進行Web開發,今後走上了Spring配置的不歸路。說句實在話,Spring是我特麼見過全部WEB工程裏面最難配的,由於必需要對它那一套非侵入的設計思想有所瞭解才能在出問題時迅速判斷是否是配置錯誤,進而定位配置錯誤所在。首先,作個簡單的總結,Spring的配置如今大體有三種:java
XML配置,時間最長,最主流,也最噁心的配置方法mysql
使用配置類+註解,推出有一段時間了,用的人很少,與其餘框架集成的時候大部分仍是繞不過XML。我的以爲沒啥卵用。程序員
Spring4新推出的Boot,對新手是友好了,可是不利於瞭解這個框架,並且遇到問題能查的資料少web
綜上,我最後仍是選擇了XML做爲開發的標配,下面以 Spring+Mybatis配置做爲示例spring
Maven依賴文件——pom.xmlsql
沒啥好講的,java程序員都知道數據庫
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>suemi</groupId> <artifactId>sbeat</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SBEAT</name> <url>http://maven.apache.org</url> <properties> <mysql.connector.version>5.1.21</mysql.connector.version> <spring.version>4.1.6.RELEASE</spring.version> <junit.version>4.12</junit.version> <velocity.version>1.6.1</velocity.version> <velocity.tools.version>2.0</velocity.tools.version> <mock.version>2.0.8</mock.version> <mybatis.version>3.3.0</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> </properties> <dependencies> <!-- velocity --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>${velocity.version}</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>${velocity.tools.version}</version> </dependency> <!-- jsp support --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <!-- just used the latest version, make sure you use the one you need --> <scope>provided</scope> </dependency> <!-- test support --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis support --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- Spring support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> </dependencies> <build> <finalName>sbeat</finalName> </build> </project>
web.xmlapache
wweb.xml規定了有哪些顯式的servlet,規定了最頂層的Context環境,是整個的綱領。它同時規定了對於哪些URL的請求歸哪些servlet處理,哪些URL使用哪一種編碼方式。須要注意的是,對於沒有人爲指定配置文件的servlet,會自動在WEB-INF文件夾下找servletName-servlet.xml的文件做爲其配置。api
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>sbeat</display-name> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>sbeat</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>sbeat</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> <!--指定Context的配置文件--> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
URL分發
這裏主要就是控制器的掃描,以及配置模板引擎,以velocity模板爲例
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--這一句處理對靜態資源的訪問--> <mvc:default-servlet-handler /> <!--這一句指定了掃描註解生成Controller的根包名--> <context:component-scan base-package="sbeat" /> <!--這一句至關於開啓註解掃描功能--> <mvc:annotation-driven /> <!--規定模板文件的類型和位置--> <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="templates/" /> <property name="velocityProperties"> <props> <prop key="input.encoding">utf-8</prop> <prop key="output.encoding">utf-8</prop> </props> </property> </bean> <!--配置附加工具,以及將後綴爲vm的文件交給下面的Resolver處理--> <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="suffix" value=".vm" /> <property name="contentType" value="text/html;charset=utf-8" /> <property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/> </bean> </beans>
toolbox.xml示例以下,您能夠選擇本身喜歡的模板引擎。
<?xml version="1.0"?><toolbox> <tool> <key>date</key> <scope>request</scope> <class> org.apache.velocity.tools.generic.DateTool </class> <parameter name="format" value="yyyy-MM-dd HH:mm:ss"/> </tool> <tool> <key>link</key> <scope>request</scope> <class>org.apache.velocity.tools.view.tools.LinkTool</class> </tool> <tool> <key>stringUtils</key> <scope>request</scope> <class>org.apache.velocity.util.StringUtils</class> </tool> <tool> <key>math</key> <scope>application</scope> <class>org.apache.velocity.tools.generic.MathTool</class> </tool> <tool> <key>esc</key> <scope>request</scope> <class>org.apache.velocity.tools.generic.EscapeTool</class> </tool> <tool> <key>params</key> <scope>request</scope> <class>org.apache.velocity.tools.view.tools.ParameterParser</class> </tool> </toolbox>
applicationContext.xml——最重要的配置文件
applicationContext.xml主要是對數據庫相關操做的一些配置,也是Spring與ORM類框架集成的節點。
<?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:p="http://www.springframework.org/schema/p" 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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <tx:annotation-driven transaction-manager="transactionManager"/> <!--開啓掃面註解生成Bean--> <context:annotation-config></context:annotation-config> <!--設定掃描的根package--> <context:component-scan base-package="sbeat" /> <!--這一段是最重要的--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--規定了掃描mapper文件的路徑--> <property name="mapperLocations" value="classpath*:sbeat/*/mapper/*.xml" /> <!--指定了Mybatis配置文件的路徑--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!--這一段讓咱們的MapperInterface可以最終在Spring中生成Bean最後被AutoWired--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="sbeat.*.mapper" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--數據庫設置--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/sbeat" /> <property name="username" value="suemi" /> <property name="password" value="123456" /> </bean> </beans>
Mybatis配置
<?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> <typeAliases> <!--POJO 類的所在package,默認類名爲其Alias--> <package name="sbeat.user.model"/> </typeAliases> <mappers> <!--映射文件所在的地方--> <mapper resource="UserMapper.xml" /> </mappers> </configuration>
Mybatis映射文件
該文件是將POJO類的
使用Spring-test測試
下面給出一個很是簡單的測試例子,應該很容易看懂,就不作解釋了
package seed.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import demo.mapper.UserMapper;import demo.model.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class TsetUserDAO { @Autowired private UserMapper userMapper; @Test public void testInsert() { User user=new User(); user.setAccount("suemi994"); user.setPasswd("123456"); userMapper.addUser(user); } }
小結
Spring經常使用的註解主要有如下幾種:
@Component
@Service--業務層
@Respority--持久化層
@Controller--視圖層
儘管這幾種註解對應的意義不同,但它們都有一個共同的做用,那就是讓Spring找到而且最終生成對應的Bean。舉個例子,咱們在Service中使用接口UserDAO,但該接口的實例咱們並無指定使用哪個,雖然咱們寫了對應的Impl Class。 經過註解生成Bean,Spring就可以在Service調用該接口的時候從容器裏獲得正確的實體對象。