Spring+SpringMVC+Mybatis+Maven搭建项目

Spring+SpringMVC+Mybatis+Maven搭建项目

http://blog.csdn.net/jintao_ma/article/details/52892625

1.前言

这篇文章一步步总结了搭建一个基于Maven的Spring+SpringMVC+Mybatis框架的完整过程,同时加入了基础工具类,包括读取配置文件,监听器和定时器等。文件可以免积分下载:http://download.csdn.net/download/jintao_ma/9661038

2.建立一个web项目

2.1 maven创建web项目

显然,由于SpringMVC的存在,表明这篇讲述的是一个Web项目,使用maven的maven-archetype-webapp这个模板,搭建一个项目,在命令行下执行:

mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=myWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

然后新建的myWebApp项目中,只有java/main目录,我们新建下面三个目录才是一个完整的maven web项目:

java/resources

test/main

test/resources

接着导入eclipse,file->import:

2.2 设置web项目的版本和jdk版本

新导入的项目的web版本默认是2.3,jdk版本是1.5;我们需要重新设置一下,设置为最新的;

修改项目目录.settings下的org.eclipse.wst.common.project.facet.core.xml,修改后如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <faceted-project>  
  3.   <fixed facet="wst.jsdt.web"/>  
  4.   <installed facet="java" version="1.8"/>  
  5.   <installed facet="jst.web" version="3.0"/>  
  6.   <installed facet="wst.jsdt.web" version="1.0"/>  
  7. </faceted-project>  

同时修改项目中的web.xml:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!DOCTYPE web-app PUBLIC  
  2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
  4. <web-app>  
  5.   <display-name>Archetype Created Web Application</display-name>  
  6. </web-app>  

改为

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <web-app version="3.0"    
  3.     xmlns="http://java.sun.com/xml/ns/javaee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee    
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    
  7.       
  8.   <display-name>Archetype Created Web Application</display-name>  
  9.   
  10. </web-app>  

2.3 maven设置

2.3.1 项目run as->maven clean报错:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -Dmaven.multiModuleProjectDirectory system property is not set  

可以设一个环境变量M2_HOME指向你的maven安装目录M2_HOME=D:\Apps\apache-maven-3.3.1,然后在Window->Preference->Java->Installed JREs->Edit,在Default VM arguments中设置-Dmaven.multiModuleProjectDirectory=$M2_HOME

2.3.2 maven update project

经过前面的几项设置,项目的web版本已经是3.0,jdk也是1.8了,也可以进行maven clean和install;但是每次在进行maven->project时,项目还会变为 web 2.3和jdk 1.5

我们还需要在pom中增加下面的配置:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <build>  
  2.     <finalName>myWebApp</finalName>  
  3.     
  4.     <plugins>  
  5.         <plugin>  
  6.             <groupId>org.apache.maven.plugins</groupId>  
  7.             <artifactId>maven-compiler-plugin</artifactId>  
  8.             <version>3.5</version>  
  9.             <configuration>  
  10.                 <source>1.8</source>  
  11.                 <target>1.8</target>  
  12.             </configuration>  
  13.         </plugin>  
  14.     </plugins>  
  15.       
  16.   </build>  

然后就可以maven-clean,maven-install;然后maven update project;就没有任何的错误和警告了。

3.加入Spring,SpringMVC和Mybatis

3.1 spring.xml

在介绍配置文件之前,先在pom.xml中引入相关的jar包,下面把这篇所有需要的依赖(包括后面所用到的定时器jar包)全部贴上来,pom.xml:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>com.mycompany.app</groupId>  
  5.   <artifactId>myWebApp</artifactId>  
  6.   <packaging>war</packaging>  
  7.   <version>1.0-SNAPSHOT</version>  
  8.   <name>myWebApp</name>  
  9.   <url>http://maven.apache.org</url>  
  10.     
  11.   <properties>  
  12.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  13.         <spring.version>[4.3.0.RELEASE,)</spring.version>  
  14.   </properties>  
  15.     
  16.   <dependencies>  
  17.     <dependency>  
  18.       <groupId>junit</groupId>  
  19.       <artifactId>junit</artifactId>  
  20.       <version>[4.10,)</version>  
  21.       <scope>test</scope>  
  22.     </dependency>  
  23.       
  24. <!-- 添加数据库驱动 -->  
  25.     <dependency>  
  26.         <groupId>mysql</groupId>  
  27.         <artifactId>mysql-connector-java</artifactId>  
  28.         <version>[5.1.39,)</version>  
  29.     </dependency>  
  30.           
  31. <!-- 添加Mybatis -->  
  32.     <dependency>  
  33.         <groupId>org.mybatis</groupId>    
  34.         <artifactId>mybatis</artifactId>    
  35.         <version>[3.4.0,)</version>    
  36.     </dependency>  
  37.           
  38. <!-- 添加mybatis-spring的依赖 -->  
  39.     <dependency>  
  40.         <groupId>org.mybatis</groupId>    
  41.            <artifactId>mybatis-spring</artifactId>    
  42.            <version>[1.3.0,)</version>  
  43.     </dependency>  
  44.       
  45. <!-- 添加Spring的依赖 -->  
  46.     <dependency>  
  47.         <groupId>org.springframework</groupId>  
  48.         <artifactId>spring-core</artifactId>  
  49.         <version>${spring.version}</version>  
  50.     </dependency>  
  51.   
  52.     <dependency>  
  53.         <groupId>org.springframework</groupId>  
  54.         <artifactId>spring-tx</artifactId>  
  55.         <version>${spring.version}</version>  
  56.     </dependency>  
  57.   
  58.     <dependency>  
  59.         <groupId>org.springframework</groupId>  
  60.         <artifactId>spring-web</artifactId>  
  61.         <version>${spring.version}</version>  
  62.     </dependency>  
  63.   
  64.     <dependency>  
  65.         <groupId>org.springframework</groupId>  
  66.         <artifactId>spring-context-support</artifactId>  
  67.         <version>${spring.version}</version>  
  68.     </dependency>  
  69.       
  70.     <dependency>  
  71.         <groupId>org.springframework</groupId>  
  72.         <artifactId>spring-context</artifactId>  
  73.         <version>${spring.version}</version>  
  74.     </dependency>  
  75.   
  76.     <dependency>  
  77.         <groupId>org.springframework</groupId>  
  78.         <artifactId>spring-webmvc</artifactId>  
  79.         <version>${spring.version}</version>  
  80.     </dependency>  
  81.   
  82.     <dependency>  
  83.         <groupId>org.springframework</groupId>  
  84.         <artifactId>spring-jdbc</artifactId>  
  85.         <version>${spring.version}</version>  
  86.     </dependency>  
  87.       
  88.     <dependency>  
  89.         <groupId>org.springframework</groupId>  
  90.         <artifactId>spring-aop</artifactId>  
  91.         <version>${spring.version}</version>  
  92.     </dependency>  
  93.       
  94.     <dependency>  
  95.         <groupId>aopalliance</groupId>  
  96.         <artifactId>aopalliance</artifactId>  
  97.         <version>[1.0,)</version>  
  98.     </dependency>  
  99.       
  100.     <dependency>  
  101.         <groupId>aspectj</groupId>  
  102.         <artifactId>aspectjweaver</artifactId>  
  103.         <version>1.5.4</version>  
  104.     </dependency>  
  105.       
  106.     <dependency>  
  107.         <groupId>aspectj</groupId>  
  108.         <artifactId>aspectjrt</artifactId>  
  109.         <version>1.5.4</version>  
  110.     </dependency>  
  111.       
  112.     <dependency>  
  113.         <groupId>cglib</groupId>  
  114.         <artifactId>cglib</artifactId>  
  115.         <version>[3.2.4,)</version>  
  116.     </dependency>  
  117. <!-- 引入jstl标签库    -->  
  118.     <dependency>  
  119.         <groupId>jstl</groupId>  
  120.         <artifactId>jstl</artifactId>  
  121.         <version>1.2</version>  
  122.     </dependency>  
  123. <!-- 引入jstl标签库    -->       
  124.     <dependency>  
  125.         <groupId>taglibs</groupId>  
  126.         <artifactId>standard</artifactId>  
  127.         <version>1.1.2</version>  
  128.     </dependency>  
  129. <!-- 配置log4j -->  
  130.     <dependency>  
  131.         <groupId>log4j</groupId>  
  132.         <artifactId>log4j</artifactId>  
  133.         <version>[1.2.17,)</version>  
  134.     </dependency>  
  135. <!-- 配置slf4j -->        
  136.     <dependency>  
  137.         <groupId>org.slf4j</groupId>  
  138.         <artifactId>slf4j-api</artifactId>  
  139.         <version>[1.7.21,)</version>  
  140.     </dependency>  
  141. <!-- 配置slf4j-log -->  
  142.     <dependency>  
  143.         <groupId>org.slf4j</groupId>  
  144.         <artifactId>slf4j-log4j12</artifactId>  
  145.         <version>[1.7.21,)</version>  
  146.     </dependency>  
  147. <!-- 配置commons-io-->  
  148.     <dependency>  
  149.         <groupId>commons-io</groupId>  
  150.         <artifactId>commons-io</artifactId>  
  151.         <version>[2.5,)</version>  
  152.     </dependency>  
  153. <!--配置quartz定时器 -->  
  154.     <dependency>  
  155.         <groupId>org.quartz-scheduler</groupId>  
  156.         <artifactId>quartz</artifactId>  
  157.         <version>[2.2.3,)</version>  
  158.     </dependency>  
  159. <!--配置quartz所依赖的jar -->  
  160.     <dependency>  
  161.         <groupId>commons-collections</groupId>  
  162.         <artifactId>commons-collections</artifactId>  
  163.         <version>[3.2.1,)</version>  
  164.     </dependency>  
  165. <!-- 配置commons-logging -->  
  166.     <dependency>  
  167.         <groupId>commons-logging</groupId>  
  168.         <artifactId>commons-logging</artifactId>  
  169.         <version>[1.2,)</version>  
  170.     </dependency>  
  171.     <dependency>  
  172.         <groupId>commons-fileupload</groupId>  
  173.         <artifactId>commons-fileupload</artifactId>  
  174.         <version>[1.3.2,)</version>  
  175.     </dependency>  
  176.           
  177.   </dependencies>  
  178.     
  179.   <build>  
  180.     <finalName>myWebApp</finalName>  
  181.       
  182.     <plugins>  
  183.         <plugin>  
  184.             <groupId>org.apache.maven.plugins</groupId>  
  185.             <artifactId>maven-compiler-plugin</artifactId>  
  186.             <version>3.5</version>  
  187.             <configuration>  
  188.                 <source>1.8</source>  
  189.                 <target>1.8</target>  
  190.             </configuration>  
  191.         </plugin>  
  192.     </plugins>  
  193.       
  194.   </build>  
  195.     
  196. </project>  

<version>[1,1)</version>这样的写法意思是获取大于等于1.1版本的最新的jar包,这样以后就不用手动升级了,每次maven->update project就可以了。

接着在配置spring.xml之前,建议先看上一篇文章的总结:http://blog.csdn.net/Jintao_Ma/article/details/52853865,spring.xml的作用就是把spring和mybatis进行集成,这篇文章的spring配置和上一篇稍有不同,首先扫描的包发生了变化

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 扫描注解,Spring的配置文件不扫描@Controller注解,因为controller层由springMvc配置文件扫描解析 -->  
  2.     <context:component-scan base-package="com.mycompany">  
  3.         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
  4.     </context:component-scan>  

这里面去掉了controller层的扫描,controller层由spring mvc来进行扫描;然后是aop配置中增加了“..”

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 添加规则事务 -->  
  2.     <aop:config proxy-target-class="true">  
  3. <!--     第一个*代表所有的返回值类型  -->  
  4. <!--     第一个..代表中间隔着任意多个包层次 -->  
  5. <!--     第二个*代表所有的类 -->  
  6. <!--     第三个*代表类所有方法 最后一个..代表所有的参数。 -->  
  7.         <aop:pointcut expression="execution(* com.mycompany..service.*.*(..))" id="txPoint"/>  
  8.         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>  
  9.     </aop:config>  

因为service层在不同的包中,我们希望只对service进行事务,com.mycompany..service代表com.mycompany项目所有目录下的名为service文件夹

3.2 web.xml

先配置spring.xml文件的读取:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml-->  
  2.     <context-param>  
  3.         <param-name>contextConfigLocation</param-name>  
  4.         <param-value>classpath:spring.xml,  
  5.         classpath:springQuartz.xml  
  6.         </param-value>  
  7.     </context-param>  
  8.     
  9.     <listener>  
  10.         <listener-class>  
  11.             org.springframework.web.context.ContextLoaderListener  
  12.         </listener-class>  
  13.    </listener>  

配置context-param,里面读取spring.xml(先忽略springQuartz.xml,后面提到), 然后监听器listener在项目初始化的时候就能够读取spring.xml中的配置,顺便说一下不同节点在web.xml中的执行顺序,context-param -> listener -> filter ->  servlet

再配置自己的servlet:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <servlet>    
  2.         <servlet-name>myWebApp</servlet-name>    
  3.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
  4.         <init-param>    
  5. <!--         默认加载/WEb-INF/<servletName-servlet>.xml的Spring配置文件,可以通过contextConfigLocation手动指定 -->    
  6.             <param-name>contextConfigLocation</param-name>    
  7.             <param-value>classpath:springMvc.xml</param-value>    
  8.         </init-param>    
  9.         <load-on-startup>1</load-on-startup>    
  10.     </servlet>    
  11.     
  12.     <servlet-mapping>    
  13.         <servlet-name>myWebApp</servlet-name>    
  14.         <url-pattern>/</url-pattern>    
  15.     </servlet-mapping>  

在分析之前,建议先看之前总结的另一篇文章:http://blog.csdn.net/Jintao_Ma/article/details/52141953,之后就可以明白上面的配置了。这时候可能会有一个疑问,这个tomcat自带的名为'jsp'的servlet, 与mvc中的视图解析器有什么关系吗?后面进行解释

3.3 springMvc.xml

先看一下视图解析器的配置,然后分析它与tomcat自带'jsp'关系

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 配置视图解析器 -->    
  2.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
  3.         <property name="prefix" value="/jsp/"></property>    
  4.         <property name="suffix" value=".jsp"></property>    
  5.     </bean>  

当我们在地址栏中输入一个地址,首先它会去找servlet,由于与‘jsp'这个servlet不匹配,所以会进入我们自己配置的默认servlet,然后进入controller层次,接着controller返回的时候,会经过试图解析器的解析,完成之后再由‘jsp’这个servlet来找到对应的jsp。 

对资源文件的处理,这篇文章用的是<default-servlet-handler/>,之后还要配置<mvc annotation-driven/>,原因看这篇文章http://www.cnblogs.com/hujingwei/p/5349983.html,配置如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <mvc:annotation-driven/>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <mvc:default-servlet-handler/>  

同时还可以配置<mvc:view-controller>,这样url请求可以不经过controller层次,直接由试图解析器进行解析,如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 加载系统配置文件,然后再mvc:view-controller中的path中引入 -->  
  2.     <context:property-placeholder location="classpath:system.properties"/>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <mvc:view-controller path="${adminPath}" view-name="index"/>  

另外需要注意一点,我们在mvc中扫描包时候,只扫描controller层的,这和spring.xml的配置正好是互补的,(或者说不要扫描service层)。 为什么mvc不能扫描service层呢,上一篇文章http://blog.csdn.net/Jintao_Ma/article/details/52853865提到了。

在springMvc.xml中还可以加入多文件上传,这样一来,springMvc.xml的完整配置如下:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"    
  5.     xmlns:context="http://www.springframework.org/schema/context"    
  6.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd    
  7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd    
  8.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">    
  9.     
  10. <!-- 加载系统配置文件,然后再mvc:view-controller中的path中引入 -->  
  11.     <context:property-placeholder location="classpath:system.properties"/>  
  12.   
  13. <!-- 配置自动扫描的包,只扫描@controller注解的包 -->    
  14.     <context:component-scan base-package="com.mycompany" use-default-filters="false">  
  15.         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  16.     </context:component-scan>    
  17.       
  18.     <mvc:view-controller path="${adminPath}" view-name="index"/>  
  19.     
  20.     <mvc:annotation-driven/>  
  21.     
  22. <!-- 配置视图解析器 -->    
  23.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
  24.         <property name="prefix" value="/jsp/"></property>    
  25.         <property name="suffix" value=".jsp"></property>    
  26.     </bean>    
  27.    
  28.     <mvc:default-servlet-handler/>  
  29.       
  30. <!-- 支持多文件上传 -->  
  31.     <bean id="multipartResolver"      
  32.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      
  33.         <!-- 默认编码 -->    
  34.         <property name="defaultEncoding" value="utf-8" />      
  35.         <!-- 文件大小最大值 -->    
  36.         <property name="maxUploadSize" value="10485760000" />      
  37.         <!-- 内存中的最大值 -->    
  38.         <property name="maxInMemorySize" value="40960" />      
  39.     </bean>   
  40.       
  41. </beans>  

4.其他配置

4.1 读取配置文件

全局配置配置文件有两个,一个是jdbc.properties, 另一个是system.properties, 后者可以放入一下系统的配置信息:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. adminPath=/main  
  2. delTempFile=E:/Majintao/temp  

配置文件加载类,PropertiesLoader.java:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mycompany.mvc.utils;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.NoSuchElementException;  
  6. import java.util.Properties;  
  7.   
  8. import org.apache.commons.io.IOUtils;  
  9. import org.slf4j.Logger;  
  10. import org.slf4j.LoggerFactory;  
  11. import org.springframework.core.io.DefaultResourceLoader;  
  12. import org.springframework.core.io.Resource;  
  13. import org.springframework.core.io.ResourceLoader;  
  14.   
  15. /**  
  16.  * @author Jintao_Ma  
  17.  * @time 2016年7月21日23:19:39  
  18.  * @description: 
  19.  * Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会 
  20.  * 覆盖之前的值,但以System的Property优先.项目的基础工具类,可被上层使用 
  21.  */    
  22. public class PropertiesLoader {    
  23.         
  24.     private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);    
  25.     
  26.     private static ResourceLoader resourceLoader = new DefaultResourceLoader();    
  27.     
  28.     private final Properties properties;    
  29.     
  30.     public PropertiesLoader(String[] resourcesPaths) {    
  31.         properties = loadProperties(resourcesPaths);    
  32.     }    
  33.     
  34.     public Properties getProperties() {    
  35.         return properties;    
  36.     }    
  37.     
  38.     /**  
  39.      * 取出Property,但以System的Property优先.  
  40.      */    
  41.     private String getValue(String key) {    
  42.         String systemProperty = System.getProperty(key);    
  43.         if (systemProperty != null) {    
  44.             return systemProperty;    
  45.         }    
  46.         return properties.getProperty(key);    
  47.     }    
  48.     
  49.     /**  
  50.      * 取出String类型的Property,但以System的Property优先,如果都為Null则抛出异常.  
  51.      */    
  52.     public String getProperty(String key) {    
  53.         String value = getValue(key);    
  54.         if (value == null) {    
  55.             throw new NoSuchElementException();    
  56.         }    
  57.         return value;    
  58.     }    
  59.     
  60.     /**  
  61.      * 取出String类型的Property,但以System的Property优先.如果都為Null則返回Default值.  
  62.      */    
  63.     public String getProperty(String key, String defaultValue) {    
  64.         String value = getValue(key);    
  65.         return value != null ? value : defaultValue;    
  66.     }    
  67.     
  68.     /**  
  69.      * 取出Integer类型的Property,但以System的Property优先.如果都為Null或内容错误则抛出异常.  
  70.      */    
  71.     public Integer getInteger(String key) {    
  72.         String value = getValue(key);    
  73.         if (value == null) {    
  74.             throw new NoSuchElementException();    
  75.         }    
  76.         return Integer.valueOf(value);    
  77.     }    
  78.     
  79.     /**  
  80.      * 取出Integer类型的Property,但以System的Property优先.如果都為Null則返回Default值,如果内容错误则抛出异常  
  81.      */    
  82.     public Integer getInteger(String key, Integer defaultValue) {    
  83.         String value = getValue(key);    
  84.         return value != null ? Integer.valueOf(value) : defaultValue;    
  85.     }    
  86.     
  87.     /**  
  88.      * 取出Double类型的Property,但以System的Property优先.如果都為Null或内容错误则抛出异常.  
  89.      */    
  90.     public Double getDouble(String key) {    
  91.         String value = getValue(key);    
  92.         if (value == null) {    
  93.             throw new NoSuchElementException();    
  94.         }    
  95.         return Double.valueOf(value);    
  96.     }    
  97.     
  98.     /**  
  99.      * 取出Double类型的Property,但以System的Property优先.如果都為Null則返回Default值,如果内容错误则抛出异常  
  100.      */    
  101.     public Double getDouble(String key, Integer defaultValue) {    
  102.         String value = getValue(key);    
  103.         return value != null ? Double.valueOf(value) : defaultValue;    
  104.     }    
  105.     
  106.     /**  
  107.      * 取出Boolean类型的Property,但以System的Property优先.如果都為Null抛出异常,如果内容不是true/false则返回false.  
  108.      */    
  109.     public Boolean getBoolean(String key) {    
  110.         String value = getValue(key);    
  111.         if (value == null) {    
  112.             throw new NoSuchElementException();    
  113.         }    
  114.         return Boolean.valueOf(value);    
  115.     }    
  116.     
  117.     /**  
  118.      * 取出Boolean类型的Property,但以System的Property优先.如果都為Null則返回Default值,如果内容不为true/false则返回false.  
  119.      */    
  120.     public Boolean getBoolean(String key, boolean defaultValue) {    
  121.         String value = getValue(key);    
  122.         return value != null ? Boolean.valueOf(value) : defaultValue;    
  123.     }    
  124.     
  125.     /**  
  126.      * 载入多个文件, 文件路径使用Spring Resource格式.  
  127.      */    
  128.     private Properties loadProperties(String[] resourcesPaths) {    
  129.         Properties props = new Properties();    
  130.     
  131.         for (String location : resourcesPaths) {    
  132.             InputStream is = null;    
  133.             try {    
  134.                 Resource resource = resourceLoader.getResource(location);    
  135.                 is = resource.getInputStream();    
  136.                 props.load(is);    
  137.             } catch (IOException ex) {    
  138.                 logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());    
  139.             } finally {    
  140.                 IOUtils.closeQuietly(is);    
  141.             }    
  142.         }    
  143.         return props;    
  144.     }    
  145. }   

配置文件工具类SystemConfig.java:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mycompany.mvc.config;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. import com.mycompany.mvc.utils.PropertiesLoader;  
  6.   
  7. /** 
  8.  *@author Jintao_Ma 
  9.  *@time 2016年7月23日14:26:12 
  10.  *@description: 
  11.  *  获取配置文件信息 
  12.  */  
  13. public class SystemConfig {  
  14.   
  15.     private static Properties properties;  
  16.       
  17.     private static String[] resourcesPaths = {"classpath:system.properties"};  
  18.       
  19.     static{  
  20.     properties = new PropertiesLoader(resourcesPaths).getProperties();  
  21.     }  
  22.       
  23.     public static String getProperty(String key){  
  24.         String systemProperty = System.getProperty(key);    
  25.         if (systemProperty != null) {    
  26.             return systemProperty;    
  27.         }    
  28.         return properties.getProperty(key);  
  29.     }  
  30. }  

然后就可以像SystemConfig.getProperty()的形式使用配置文件中的属性了。

4.2 设置监听器

监听器可以做很多事情,比如我们可以在系统加载的时候获取系统的绝对路径,然后放入System中,SystemListener.java:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mycompany.mvc.listener;  
  2.   
  3. import javax.servlet.ServletContextEvent;  
  4. import javax.servlet.ServletContextListener;  
  5.   
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8.   
  9. public class SystemListener implements ServletContextListener{  
  10.   
  11.     private Logger logger = LoggerFactory.getLogger(SystemListener.class);  
  12.       
  13.     /** 
  14.      * 获取系统绝对路径 
  15.      */  
  16.     @Override  
  17.     public void contextInitialized(ServletContextEvent servletContext) {  
  18.         logger.debug("servletContext init start...");  
  19.         System.setProperty("realPath", servletContext.getServletContext().getRealPath("/"));  
  20.         logger.debug("servletContext init end...");  
  21.     }  
  22.       
  23.     @Override  
  24.     public void contextDestroyed(ServletContextEvent arg0) {  
  25.           
  26.     }  
  27. }  

4.3 设置定时器

新建springQuartz.xml,在其中指定扫描的包,以及执行的方法和时间等 :

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?> <beans  
  2.     xmlns = "http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  8.         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd      
  9.         http://www.springframework.org/schema/context      
  10.         http://www.springframework.org/schema/context/spring-context-4.3.xsd  
  11.         http://www.springframework.org/schema/aop    
  12.         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">   
  13.   
  14.     <context:component-scan base-package="com.mycompany.mvc.quartz"></context:component-scan>  
  15.   
  16. <!-- 任务生成器,指定其对应的对象和其中的方法 -->  
  17.     <bean id="fileDeleteDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  18.         <property name="targetObject" ref="fileDelete" />  
  19.         <property name="targetMethod" value="fileDelete_delFile" />  
  20.     </bean>  
  21. <!-- 触发器生成器,指定任务和执行的时间 -->  
  22.     <bean id="fileDeleteTrigger"  class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
  23.         <property name="jobDetail" ref="fileDeleteDetail" />  
  24.         <property name="cronExpression">  
  25.             <value>0 0/5* * * ?</value><!-- 每隔五分钟跑一次,删除指定目录下的文件 -->  
  26.         </property>  
  27.     </bean>  
  28.     <bean id="schedulerFactoryBean"  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  29.         <property name="triggers">  
  30.             <list>  
  31.                 <ref bean="fileDeleteTrigger" />  
  32.             </list>  
  33.         </property>  
  34.     </bean>  
  35.           
  36. </beans>  

接着再web.xml中读取,这就是前面提到的:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <context-param>  
  2. <param-name>contextConfigLocation</param-name>  
  3.     <param-value>classpath:spring.xml,  
  4.     classpath:springQuartz.xml  
  5.     </param-value>  
  6. </context-param>  

然后定时器就设置好了,它所指定的类,和要执行的方法是下面这个,FileDelete.java:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.mycompany.mvc.quartz;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.springframework.stereotype.Component;  
  6.   
  7. import com.mycompany.mvc.config.SystemConfig;  
  8.   
  9. /** 
  10.  * @author Jintao_Ma 
  11.  * @time 2016年7月25日21:45:35 
  12.  * @description: 
  13.  *  文件删除类,可删除多个文件夹下的文件 
  14.  */  
  15.   
  16. @Component("fileDelete")  
  17. public class FileDelete {  
  18.   
  19.     private String folder = SystemConfig.getProperty("delTempFile");  
  20.       
  21.     private String[] folders={folder};  
  22.       
  23.     private static void delFiles(String[] folders) {  
  24.         for (int i = 0; i < folders.length; i++) {  
  25.             File f = new File(folders[i]);  
  26.             File[] files = null;  
  27.             if (f.exists()) {  
  28.                 files = f.listFiles();  
  29.                 for (int j = 0; j < files.length; j++) {  
  30.                     files[j].delete();  
  31.                 }  
  32.             }  
  33.         }  
  34.     }  
  35.       
  36.     public void fileDelete_delFile(){  
  37.         delFiles(folders);  
  38.     }  
  39. }  

就是删除E:/Majintao/temp下面所有的文件夹,每5分钟查询一次。 (这个temp是我的临时文件夹 ^_^)

5.总结

一个基本的基于maven的spring+mvc+mybatis框架就搭建好了,需要增加的东西还有很多,后面可以根据需要慢慢的往其中增加其他的一些东西,以后会继续总结~  下面是本篇讲述项目的的基本结构:

PS:上一篇文章提到了事务的配置应该在service层,而且应抛出异常让controller层try...catch处理。还应该注意一点是,由于controller层没有事务,所以一个方法里应该只有一个service层的方法,也就是说一个service层的方法,应该完成一个完整的业务。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值