整理一下今年用过的SpringMVC及相关组件的配置
Spring版本4.2.0.RELEASE
web.xml版本3.0
GroupId为personal.cat
第一部分、基本配置
1、Spring+SpringMVC的骨架
依赖jar包
<!--Spring核心容器beans context context-support core expression--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <!--Spring面向切面编程--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!--Spring装配与发布--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</artifactId> <version>${spring.version}</version> </dependency> <!--Spring数据库访问与集成--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</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-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!--Spring测试--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--SpringWeb与远程调用--> <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-webmvc-portlet</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <!--使用RequestBody和ResponseBody时Java实例与Json转化相关包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.3</version> </dependency>
web.xml的基础配置(仅配置Spring和SpringMVC容器、编码过滤器)
<?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" version="3.0"> <!--启动页面--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--配置session过期时间(单位为分钟)--> <session-config> <session-timeout>360</session-timeout> </session-config> <!-- 配置监听器ContextLoaderListener 在Web容器启动时该监听器会监听到启动事件从而执行它所实现的ServletContextListener方法 它是Spring容器创建的发起者 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- ContextLoaderListener的配置文件 在param-value节点内声明配置文件的路径 如果有多个配置文件可以用","隔开,也可以用applicationContext-*.xml这样的通配符 如果不声明context-param,默认的路径是"/WEB-INF/applicationContext.xml",文件名称必须严格匹配且大小写敏感 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml,classpath:spring/applicationContext-*.xml</param-value> </context-param> <!-- 配置SpringMVC的DispatcherServlet DispatcherServlet会自动拦截匹配规则的请求路径并分发到相应的Controller层处理 --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- DispatcherServlet的配置文件 在param-value节点内声明配置文件的路径 如果有多个配置文件可以用","隔开,也可以用dispatcher-servlet-*.xml这样的通配符 如果不声明context-param,默认的路径是"/WEB-INF/<servlet-name>-servlet.xml",文件名称必须严格匹配且大小写敏感 --> <param-value>classpath:spring/dispatcher-servlet.xml,classpath:spring/dispatcher-servlet-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <!--配置DispatcherServlet拦截请求路径的规则--> <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> <init-param> <!--是否检查request.getCharacterEncoding()方法--> <param-name>forceEncoding</param-name> <!--true则强制覆盖之前的编码格式--> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 注册properties文件的占位符使Spring管理的SpringBean可以通过@Value("${key}")的方式直接引入配置文件中的数据 为避免中文乱码,file-encoding设置为properties文件的编码格式 --> <context:property-placeholder location="classpath:*.properties" file-encoding="GBK"/> <!-- 启动Spring的组件扫描 Spring通过扫描base-package下的Java类,通过注解来决定是否注册为SpringBean 当存在多个包路径时可以使用","隔开 这里通过配置过滤器让Spring在扫描包时忽略掉@Controller注解的Java类留给SpringMVC管理 --> <context:component-scan base-package="personal.cat.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
SpringMVC容器的配置文件dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 注册properties文件的占位符使SpringMVC管理的SpringBean可以通过@Value("${key}")的方式直接引入配置文件中的数据 为避免中文乱码,file-encoding设置为properties文件的编码格式 --> <context:property-placeholder location="classpath:*.properties" file-encoding="GBK"/> <!-- 启动Spring的组件扫描 Spring通过扫描base-package下的Java类,通过注解来决定是否注册为SpringBean 当存在多个包路径时可以使用","隔开 这里通过配置过滤器让SpringMVC在扫描包时只装载@Controller注解的JavaBean --> <context:component-scan base-package="personal.cat.*" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- SpringMVC高级注解驱动 该驱动会默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个Bean, 使Controller层可以使用@RequestMapping、@NumberFormatAnnotation、@DateTimeFormat、@Valid等注解并支持Jaxb和Json解析 --> <mvc:annotation-driven/> <!-- 对静态资源访问的过滤 静态资源要统一放在webApp的static文件夹下 --> <mvc:resources mapping="/static/**" location="/static/"/> <!--注册视图解析器,在没有注解为@ResponseBody时自动为字符串返回值加上/前缀和.jsp后缀--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
第二部分、额外的组件
基于web.xml的配置,后续的文件命名将符合applicationContext-*.xml和dispatcher-servlet-*.xml这两种格式
由于applicationContext.xml和dispatcher-servlet.xml已经注册了所有的.properties配置文件的占位符,后续的配置中无需再次引入
1、集成MongoDB
依赖jar包
<!--Spring集成Mongodb--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.7.2.RELEASE</version> </dependency>
装载MongoTemplate的配置文件applicationContext-mongo.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:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"> <!--配置MongoDB客户端--> <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.userName}:${mongo.password}@${mongo.database}"> <mongo:client-options write-concern="SAFE" connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" socket-timeout="${mongo.socketTimeout}"/> </mongo:mongo-client> <!-- 注册MongoTemplate 使用配置好的MongoDB客户端实例化MongoTemplate交给Spring容器管理 MongoTemplate内部实现了连接池且线程安全 --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoClient"/> <constructor-arg value="${mongo.databaseName}"/> </bean> </beans>
配置文件引用的mongo.properties
#主机ip地址 mongo.host=127.0.0.1 #主机端口 mongo.port=27017 #鉴权数据库名称 mongo.database=admin #访问账号 mongo.userName=root #访问密码 mongo.password=root #操作数据库名称 mongo.databaseName=test #主机允许连接数量 mongo.connectionsPerHost=10 #主机允许的阻塞线程倍数,例如当前允许10个连接,那么最大允许阻塞40个线程的访问 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #数据库连接超时时间 mongo.connectTimeout=1500 #获取连接最大等待时间 mongo.maxWaitTime=15000 #查询超时时间 mongo.socketTimeout=15000
2、集成Mybatis(连接池管理为Druid)
依赖jar包
<!--Spring集成Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--Druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency>
装载SqlSessionFactoryBean的配置文件applicationContext-jdbc.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 注册数据源 数据源的连接池管理是Druid --> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="name" value="${jdbc.name}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="${jdbc.maxPoolPreparedStatementPerConnectionSize}"/> <property name="validationQuery" value="${jdbc.validationQuery}"/> <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/> <property name="testOnReturn" value="${jdbc.testOnReturn}"/> <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> <property name="filters" value="${jdbc.filters}"/> </bean> <!--注册Mybatis的核心类SqlSessionFactoryBean--> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--指定数据源--> <property name="dataSource" ref="druidDataSource"/> <!-- 指定需要扫描的包路径 使Mybatis的mapper文件在声明ResultType时可以使用类名作为别名而不是实体类的全路径 --> <property name="typeAliasesPackage" value="classpath:personal.cat.entity"/> <!--指定sql映射文件的路径--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定SqlSessionFactoryBean,如果当前上下文中只定义了一个则该属性可省略--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/> <!--指定持久层的接口路径--> <property name="basePackage" value="personal.cat.dao"/> </bean> <!--注册Spring的数据源事务管理器--> <bean name="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="druidDataSource"/> </bean> <!--启动注解式事务驱动--> <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/> </beans>
配置文件引用的jdbc.properties
这里以Mysql为例,使用时需要额外引入mysql-connector-java包,否则ClassLoader在加载com.mysql.jdbc.Driver时会抛出ClassNotFoundException
#数据源名称 jdbc.name=druidDataSource #主机ip地址 jdbc.host=127.0.0.1 #主机端口 jdbc.port=3306 #操作数据库名称 jdbc.database=test #数据库连接路径 #jdbc.url=jdbc:microsoft:sqlserver://${jdbc.host}:${jdbc.port};database=${jdbc.database} #jdbc.url=jdbc:oracle:thin:@//${jdbc.host}:${jdbc.port}/${jdbc.database} jdbc.url=jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useUnicode=true&characterEncoding=UTF-8 #访问账号 jdbc.username=root #访问密码 jdbc.password=root #数据库驱动全路径名 #jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver #jdbc.driverClassName=oracle.jdbc.driver.OracleDriver jdbc.driverClassName=com.mysql.jdbc.Driver #Druid连接池初始化连接数量 jdbc.initialSize=1 #Druid连接池可用连接数量上限 jdbc.maxActive=10 #Druid连接池最小空闲连接 jdbc.minIdle=1 #Druid连接池获取连接最大等待时间 jdbc.maxWait=15000 #Druid连接池是否开启PreparedStatement缓存池 jdbc.poolPreparedStatements=false #Druid连接池PreparedStatement缓存池大小(当该项的值大于0时默认启动PreparedStatement缓存池) jdbc.maxPoolPreparedStatementPerConnectionSize=-1 #Druid连接池校验连接可用的查询sql jdbc.validationQuery=SELECT 1 #Druid连接池获取连接时是否校验 jdbc.testOnBorrow=true #Druid连接池归还连接时是否校验 jdbc.testOnReturn=false #Druid连接池连接空闲时是否校验 jdbc.testWhileIdle=true #Druid连接池每次扫描空闲连接的时间间隔 jdbc.timeBetweenEvictionRunsMillis=60000 #Druid连接池连接允许的最小空闲时间 jdbc.minEvictableIdleTimeMillis=300000 #Druid连接池通过别名的方式配置扩展插件,常用的插件:1、监控统计stat 2、日志log4j 3、防御sql注入wall jdbc.filters=stat
原文地址:https://www.cnblogs.com/paranoidCAT/p/10262473.html
时间: 2024-10-31 12:56:13