springmvc.xml,context.xml和web.xml


1:springmvc.xml配置要點

一般它主要配置Controller的組件掃描器和視圖解析器

下為:springmvc.xml文件

 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:p="http://www.springframework.org/schema/p" 
 5     xmlns:context="http://www.springframework.org/schema/context" 
 6     xmlns:mvc="http://www.springframework.org/schema/mvc" 
 7     xmlns:task="http://www.springframework.org/schema/task"
 8     xsi:schemaLocation="
 9         http://www.springframework.org/schema/beans 
10         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
11         http://www.springframework.org/schema/context 
12         http://www.springframework.org/schema/context/spring-context-4.2.xsd 
13         http://www.springframework.org/schema/mvc 
14         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
15         http://www.springframework.org/schema/task 
16         http://www.springframework.org/schema/task/spring-task-4.2.xsd">    
17       <!--spring.xml文件:一般它主要配置Controller的組件掃描器和視圖解析器  -->
18         <!-- 使用注解開發,不用配置controller,需要配置一個組件掃描器 -->  
19         <context:component-scan base-package="com.edu.test.controller"/>
20         
21         <!--*************** 支持aop **************** -->
22         <aop:aspectj-autoproxy proxy-target-class="true" />
23          
24         <mvc:resources location="/img/" mapping="/img/**" />
25         <!-- /js/文件夾下的文件不需要攔截 -->
26         <mvc:resources location="/js/" mapping="/js/**" />
27         <!-- /css/文件夾下的文件不需要攔截 -->
28         <mvc:resources location="/css/" mapping="/css/**" />
29     
30         <!-- 支持用注解的方式驗證參數格式正確性 -->  
31         <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />
32         <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
33         <!-- <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/> -->
34         <!--不設置則默認為classpath下的 ValidationMessages.properties
35         <property name="validationMessageSource" ref="validatemessageSource"/> -->
36         </bean>
37         <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
38         <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
39             <property name="basename" value="classpath:validatemessages"/>  
40             <property name="fileEncodings" value="utf-8"/>  
41             <property name="cacheSeconds" value="120"/>
42         </bean>
43         
44         <!-- 攔截器 -->
45         <mvc:interceptors>
46             <mvc:interceptor>
47                 <mvc:mapping path="/api/*"/>
48                 <bean class="com.parry.test.interceptor.SignatureCheckInterceptor"></bean>
49             </mvc:interceptor>
50             <mvc:interceptor>
51                 <mvc:mapping path="/web/*"/>
52                 <bean class="com.parry.test.interceptor.AccessCheckInterceptor"></bean>
53             </mvc:interceptor>
54         </mvc:interceptors>
55         <mvc:annotation-driven>
56         </mvc:annotation-driven>
57     
58         <!-- 視圖解析器 -->                
59         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
60             <!-- 配置從項目根目錄到指定目錄一端路徑 ,建議指定淺一點的目錄-->
61             <property name="prefix" value="/WEB-INF/jsp/"></property>
62             <!-- 文件的后綴名 -->
63             <property name="suffix" value=".jsp"></property>
64         </bean>
65         
66           <!-- 文件上傳配置 -->
67         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
68              <!-- 設置上傳文件的最大尺寸為1MB -->
69              <property name="maxUploadSize">  
70                 <value>1048576</value>  
71             </property>
72             <property name="defaultEncoding">
73                 <value>UTF-8</value>
74             </property> 
75         </bean>
76 </beans>

 

2:applicationContext.xml配置要點(在web.xml文件需要加<listener>)

下為:applicationContext.xml文件

  1 <beans xmlns="http://www.springframework.org/schema/beans"
  2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xmlns:context="http://www.springframework.org/schema/context"
  4     xmlns:aop="http://www.springframework.org/schema/aop"
  5     xmlns:tx="http://www.springframework.org/schema/tx"
  6     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  8         http://www.springframework.org/schema/context
  9        http://www.springframework.org/schema/context/spring-context-4.2.xsd
 10        http://www.springframework.org/schema/aop
 11        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
 12        http://www.springframework.org/schema/tx
 13        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
 14      <!-- 配置組件掃描器,使用注解方式開發,不用配置dao和service -->      <!-- 在springmvc.xml文件中也可以配置這個屬性 -->  
 15      <context:component-scan base-package="com.edu.test"/>
 16       
 17     <!-- 數據庫配置 -->
 18     <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
 19         destroy-method="close">
 20         <property name="driverClass" value="com.mysql.jdbc.Driver" />
 21          <!-- 測試數據庫 -->
 22         <property name="jdbcUrl"  value="jdbc:mysql://127.0.0.1:3066/TESTDB?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true" />
 23         <property name="username" value="root" />
 24         <property name="password" value="root" />
 25         
 26         <!-- 檢查數據庫連接池中空閑連接的間隔時間,單位是分,默認值:240,如果要取消則設置為0 -->
 27         <property name="idleConnectionTestPeriod" value="240" />
 28         <!-- 連接池中未使用的鏈接最大存活時間,單位是分,默認值:30,如果要永遠存活設置為0 -->
 29         <!-- 數據庫連接池過期時間應小於等於mysql的過期時間和mycat的過期時間 -->
 30         <property name="idleMaxAge" value="20" />
 31         <!-- 每個分區最大的連接數 -->
 32         <property name="maxConnectionsPerPartition" value="100" />
 33         <!-- 每個分區最小的連接數 -->
 34         <property name="minConnectionsPerPartition" value="20" />
 35         <!-- 分區數 ,默認值2,最小1,推薦3-4,視應用而定 -->
 36         <property name="partitionCount" value="1" />
 37         <!-- 每次去拿數據庫連接的時候一次性要拿幾個,默認值:2 -->
 38         <property name="acquireIncrement" value="2" />
 39         <!-- 緩存prepared statements的大小,默認值:0 -->
 40         <property name="statementsCacheSize" value="0" />
 41         <property name="connectionTimeoutInMs" value="100" />
 42         <!-- 每個分區釋放鏈接助理進程的數量,默認值:3,除非你的一個數據庫連接的時間內做了很多工作,不然過多的助理進程會影響你的性能 -->
 43         <property name="releaseHelperThreads" value="3" />
 44     </bean>
 45     <!-- 配置SqlSessionFactoryBean -->
 46     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 47         <property name="dataSource" ref="dataSource" />
 48         <property name="configLocation" value="classpath:mybatis.xml" />
 49         <!-- mapper和resultmap配置路徑 -->
 50         <property name="mapperLocations">
 51             <list>
 52                 <!-- 表示在com.sfpay.mapper包或以下所有目錄中,以-resultmap.xml結尾所有文件 -->
 53                 <value>classpath:com/parry/test/dao/config/*.xml</value>
 54             </list>
 55         </property>
 56     </bean>
 57     <!-- 使用接口類實現mybatis mapper接口 https://blog.csdn.net/Edison_03/article/details/72796691 -->
 58     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 59         <property name="basePackage" value="com.cn21.calendar.dao" />
 60         <!--下面這個省略掉的話也不會出錯,建議保留它-->
 61         <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
 62         <!--下面這個省略掉的話也不會出錯,建議保留它-->
 63         <property name="annotationClass" value="framework.database.annotation.Dao"/>
 64         <!-- -->
 65     </bean>
 66     <!--使用模板類實現mybatis -->
 67     <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 68         <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
 69         <constructor-arg name="executorType" value="BATCH"></constructor-arg>
 70         <constructor-arg name="exceptionTranslator" ref="myBatisExceptionTranslator"></constructor-arg>
 71     </bean>
 72    
 73     <!-- 事務配置 -->
 74     <bean id="transactionManager"
 75         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 76         <property name="dataSource" ref="dataSource" />
 77     </bean>
 78     <!-- 用於持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的靜態方法得到spring 
 79         bean對象 -->
 80     <bean class="com.parry.test.springcontext.SpringContextHolder" lazy-init="false" />
 81 
 82     
 83     <!-- 配置AOP通知 -->
 84     <tx:advice id="txAdvice" transaction-manager="transactionManager">
 85          <!-- 配置事務屬性 -->
 86          <tx:attributes>
 87              <!-- 添加事務管理的方法 -->
 88              <tx:method name="save*" propagation="REQUIRED"/>
 89              <tx:method name="delete*" propagation="REQUIRED"/>
 90              <tx:method name="update*" propagation="REQUIRED"/>
 91              <tx:method name="select*" read-only="true"/>
 92          </tx:attributes>
 93      </tx:advice>
 94      
 95      <!-- 配置AOP,為添加事務管理的操作配置AOP -->
 96     <aop:config>
 97         <!-- 引入的Spring定義的事務通知,需要使用aop:advisor -->
 98         <!-- 下面難 -->
 99         <aop:advisor advice-ref="txAdvice"
100             pointcut="execution(* com.edu.test.service.*.*(..))"
101         />
102     </aop:config>
103     <!-- 服務器啟動,初始化項目配置參數 -->
104     <bean name="InitalizeBean" class="com.parry.test.configure.impl.InitalizeBean" />
105       <!-- 定時器 begin -->
106     <!-- 賽程 調度業務對象 -->
107     <bean id="deletePastOrderJob" class="com.parry.test.function.PublicTypeFunction" />
108     <!-- 賽程 調度業務 -->
109     <bean id="deletePastOrderTask"
110         class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
111         <property name="targetObject" ref="deletePastOrderJob" />
112         <property name="targetMethod" value="deletePastOrder" />
113     </bean>
114     <!-- 賽程 調度器觸發器 每天早上07:00執行一次 -->
115     <bean id="deletePastOrderTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
116         <property name="jobDetail" ref="deletePastOrderTask" />
117         <property name="cronExpression" value="0 13 09 * * ? *" />
118     </bean>
119     <!-- 設置調度 -->
120     <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
121         <property name="triggers">
122             <list>
123                 <!-- <ref bean="deletePastOrderTaskTrigger" /> -->
124             </list>
125         </property>
126     </bean>
127     <!-- 定時器 end -->
128 </beans>

這里簡單介紹一下spring的配置文件applicationContext.xml中的一些配置的作用。

<context:component-scan base-package=""/>

表示啟動spring的組件掃描功能(從spring2.5版本開始)。即掃描base-package包或者子包下面的Java文件,如果掃描到有@controller、@Service、@Repository、@Component等注解的java類,就會將這些bean注冊到工廠中。還可以使用分號來分隔多個掃描包。 

如果在配置文件中配置了<context:component-scan />,就不用在配置<context:annotation-config/>,因為前者已經包含了后者。<context:annotation-config/>的作用是向spring容器注入AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及RequiredAnnotationBeanPostProcessor 四個beanPostProcessor。從而使得@Autowired等注解生效。

<mvc:annotation-driven />

<mvc:annotation-driven />是告知Spring,我們啟用注解驅動。然后Spring會自動為我們注冊DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter等幾個Bean到工廠中,此時我們可以使用@RequestMapping、@Valid注解來處理請求,也可以使用@ResponseBody來處理返回結果。

 

復制代碼
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>/WEB-INF/mail.properties</value>  
    <value>classpath: conf/sqlmap/jdbc.properties</value></list>
  </property>
</bean>
復制代碼

PropertyPlaceholderConfigurer可以將上下文(配置文件)中的屬性值放在另一個單獨的標准java Properties文件中去。在XML文件中用${key}替換指定的properties文件中的值。這樣的話,只需要對properties文件進 行修改,而不用對xml配置文件進行修改。

上面有兩種value的寫法,其中classpath是引用src目錄下的文件寫法。

<bean scope="singleton" id="dataSource"    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />        
</bean>

DriverManager類的主要作用是管理注冊到DriverManager中的JDBC驅動程序,並根據需要使用JDBC驅動程序建立與數據服務器的網絡連接。

DriverManagerDataSource在每個連接請求時都新建一個連接,但是建立與數據庫的連接是一項較耗資源的工作,頻繁的進行數據庫連接建立操作會產生較大的系統開銷,為了解決上述問題,可以采用數據庫連接池技術,例如dbcp、c3p0、druid(spring配置數據庫連接池druid)。

復制代碼
<!-- 配置mybatis的SessionFactory -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:conf/mybatis-config.xml" />
        <property name="mapperLocations">
            <array>
                <value>classpath:com/wdcloud/fayu/mapper/*Mapper.xml</value>
            </array>
        </property>
        <!-- 配置此項則在mapper中可以直接使用實體類名,而不需要使用全路徑名 -->
        <property name="typeAliasesPackage" value="com.wdcloud.fayu.entity" />
    </bean>

    <!-- 自動掃描注冊mapper接口類(接口類實現mybatis) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wdcloud.fayu.mapper" />
    </bean>

   <!-- sqlSessionTemplate配置(模板類實現mybatis) -->
   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
復制代碼

上面為mybatis在spring中的配置,其中有兩種實現方式:接口類實現和模板類實現。

接口類實現: mybatis-spring效仿spring的風格提供了一個模板類SqlSessionTemplate,可以通過模板類輕松訪問數據庫,但是這種方法使用字符串指定映射項,容易引起錯誤,因為字符串本身沒有語義性,如果存在編寫錯誤,編譯器無法識別,只能在運行期發現。

模板類實現:接口的名稱和映射命名空間相同,接口方法和映射基的id相同,MapperScannerConfigurer將掃描basePackage所指定的包下的所有的接口類(包括子包),如果它們在sql映射文件中定義過,則將它們動態定義為Spring Bean,這樣我們就可以在Service中直接注入映射接口的bean了。

SqlSessionFactoryBean是mybatis的核心管理類,通過dataSource指定數據源,configLocation指定mybatis的配置文件,mapperLocations指定mapper的xml文件。

MapperScannerConfigurer的作用是自動掃描注冊mapper接口類到spring工廠中,當你的mapper接口類存在於多個目錄下時,basePackage的值可以配置成多個目錄,中間用英文逗號隔開即可。

SqlSessionTemplate的作用是基於持久化模板類實現Mybatis(具體實現步驟)。

 

3:在web.xml文件中,將springmvc.xml和applicationContext.xml一起引入

下為:web.xm文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5     id="WebApp_ID" version="3.0">
 6     <!-- 配置監聽器 -->
 7     <listener>
 8         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 9     </listener>
10     <context-param>
11         <param-name>contextConfigLocation</param-name>
12         <param-value>classpath:applicationContext.xml</param-value>
13     </context-param>
14     
15     <!-- 中央控制器 -->
16     <servlet>
17         <servlet-name>springmvc</servlet-name>
18         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
19         <init-param>
20             <param-name>contextConfigLocation</param-name>
21             <param-value>classpath:springmvc.xml</param-value>
22         </init-param>
23     </servlet>
24     <servlet-mapping>
25         <servlet-name>springmvc</servlet-name>
26         <url-pattern>*.do</url-pattern>
27     </servlet-mapping>
28     
29     
30     <!-- 配置Spring提供的字符編碼過濾器 -->
31     <filter>
32         <filter-name>SpringCharacterEncodingFilter</filter-name>
33         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
34         <init-param>
35             <param-name>encoding</param-name>
36             <param-value>UTF-8</param-value>
37         </init-param>
38     </filter>
39     <filter-mapping>
40         <filter-name>SpringCharacterEncodingFilter</filter-name>
41         <url-pattern>*.do</url-pattern>
42     </filter-mapping>
43 </web-app>

 

原文鏈接:http://www.cnblogs.com/kaiwen1/p/6864458.html

https://www.cnblogs.com/Jason-Xiang/p/6544188.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM