当前位置: 首页 > 工具软件 > mongo-tx > 使用案例 >

整合spring+spring-data-mongo

顾嘉德
2023-12-01

目前需要用到mongodb搭建一个web服务应用,现整合出一个spring+spring mvc+spring-data的整合配置。

maven pom.xml

<span style="white-space:pre">	</span><properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- spring版本号 -->
		<spring.version>4.1.1.RELEASE</spring.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.13</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>

		<!-- servlet api jar -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<!-- jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<!-- 文件上传 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>

		<!-- fastJson json数组有关的 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.26</version>
		</dependency>

		<!-- 使用 Jackson 把 Java 对象转换成 JSON 字串 -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.11</version>
		</dependency>

		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>


		<!-- aspectjweaver.jar这是Spring AOP所要用到的包 -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.1</version>
		</dependency>


		<!-- spring mvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- spring3 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</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-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</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-expression</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-test</artifactId>
			<version>${spring.version}</version>
		</dependency>


		<!-- spring-data-mongodb相关 -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.8.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.6.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
本处用到的版本是4.1.1版本,旧版本启动不了spring-data 1.8.1版本,缺少几个方法,此处测试到的最低版本就是4.1.1

下面是web.xml

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>XXXX</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<!-- -->
	<context-param>
		<param-name>log4jRefreshInterval</param-name>
		<param-value>60000</param-value>
	</context-param>
	<!-- -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- -->
	<context-param>
		<param-name>log4jExposeWebAppRoot</param-name>
		<param-value>false</param-value>
	</context-param>
	<!-- -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
	<!-- -->
	<error-page>
		<error-code>500</error-code>
		<location>/errors/error500.html</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/errors/error404.html</location>
	</error-page>
	<error-page>
		<error-code>403</error-code>
		<location>/errors/error403.html</location>
	</error-page>
	<!-- -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
            classpath:applicationContext.xml,
<!--             classpath:springSecurityContext.xml -->
			classpath:mongo.xml
        </param-value>
	</context-param>

	<!-- <listener> -->
	<!-- <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class> -->
	<!-- </listener> -->
	<!-- -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- -->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- -->
<!-- 	<filter> -->
<!-- 		<filter-name>springSecurityFilterChain</filter-name> -->
<!-- 		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -->
<!-- 	</filter> -->

<!-- 	<filter-mapping> -->
<!-- 		<filter-name>springSecurityFilterChain</filter-name> -->
<!-- 		<url-pattern>/*</url-pattern> -->
<!-- 	</filter-mapping> -->

	<!-- -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- -->
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<!-- -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<servlet-name>XXXX</servlet-name>
	</filter-mapping>
	<!-- -->
	<servlet>
		<servlet-name>XXXX</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>XXXX</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>CacheForWeek</filter-name>
		<filter-class>me.project.XXXX.filter.ResponseHeaderFilter</filter-class>
		<init-param>
			<param-name>Cache-Control</param-name>
			<param-value>max-age=604800, public</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CacheForWeek</filter-name>
		<url-pattern>/images/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>CacheForWeek</filter-name>
		<url-pattern>/css/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>CacheForWeek</filter-name>
		<url-pattern>/js/*</url-pattern>
	</filter-mapping>
	<!-- -->
	<servlet>
		<servlet-name>default</servlet-name>
		<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
		<init-param>
			<param-name>debug</param-name>
			<param-value>0</param-value>
		</init-param>
		<init-param>
			<param-name>listings</param-name>
			<param-value>false</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.css</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.gif</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.jpg</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.ico</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.png</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>
</web-app>

XXXX是项目名,包名也随便改了下,自行修改即可,security此处就先屏蔽。

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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
					    http://www.springframework.org/schema/aop
					    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd                    
                        http://www.springframework.org/schema/context   
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
					    http://www.springframework.org/schema/tx
					    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
	
	<!-- 对包进行扫描 -->
	<context:component-scan base-package="me.project.XXXX.pojo"/>
	<context:component-scan base-package="me.project.XXXX.dao.impl"/>
	<context:component-scan base-package="me.project.XXXX.service.impl"/>
<!-- 	<context:component-scan base-package="me.project.XXXX.controller" /> -->
	
	<!-- 请求处理的映射,找到相应的Controller类 -->
	<bean id="handlerMapping"
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
	</bean>

	<!-- 处理请求的映射,即可以通过url找到相应的Controller类的方法 -->
	<bean id="annotationMethodHandlerAdapter"
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
			<!-- 下面的类已经过期 -->
<!-- 				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> -->
				<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
				<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
				<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
				<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
				<bean class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/html;charset=UTF-8</value>
						</list>
					</property>
				</bean>
				<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
			</list>
		</property>
	</bean>
			
	<!--  缓存管理  -->
<!-- 	<bean id="cacheManager" -->
<!-- 		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> -->
<!-- 		<property name="configLocation"> -->
<!-- 			<value>classpath:ehcache.xml</value> -->
<!-- 		</property> -->
<!-- 	</bean> -->


	<!-- 在此进行自动代理配置 -->
	<bean id="beanNameAutoProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="proxyTargetClass" value="true" />
		<property name="beanNames">
			<list>
				<value>*Impl</value>
			</list>
		</property>
	</bean>
	
	<!-- 文件上传-->
	<bean id="multipartResolver"  class="me.project.XXXX.util.MyMultipartResolver">
<!--     one of the properties available; the maximum file size in bytes -->
    	<property name="maxUploadSize" value="9000000"/>
	</bean>
		
</beans>
缓存此处屏蔽

下面是mongo配置

<?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:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
          ">

	<context:property-placeholder location="classpath:mongo.properties" />
	<!-- 设置mongo的连接地址 -->
	<mongo:mongo id="mongo" replica-set="${mongo.host}">
		<!-- mongodb 连接属性 -->
		<mongo:options connections-per-host="${mongo.connectionsPerHost}"
			threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
			auto-connect-retry="${mongo.retry}" />
	</mongo:mongo>
	
	<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
	<mongo:db-factory dbname="${mongo.dataname}" mongo-ref="mongo" />
	
	<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
      <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
     
    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
    <mongo:mapping-converter base-package="me.project.XXXX.pojo**" />
     
    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
    <mongo:repositories base-package="me.project.XXXX.dao**"/>
 
    <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
    <context:annotation-config />

</beans>

mongo.properties

#mongodb
mongo.dataname=tour
mongo.host=192.168.1.76:27017
mongo.connectionsPerHost=10
mongo.threadsAllowedToBlockForConnectionMultiplier=5
mongo.retry=true

具体的自己根据自己的情况配置就行了


XXXX-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-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"
	default-autowire="byName">

	<!--①:规约所有进行扫描的类,以完成Bean创建和自动依赖注入的功能-->
	<context:component-scan base-package="me.project.XXXX.controller**" />
	
	<!-- 默认的注解映射的支持 -->	
	<mvc:annotation-driven>   
    <mvc:message-converters>     
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">     
            <property name="supportedMediaTypes">     
                <list>     
                    <value>text/plain;charset=UTF-8</value>     
                    <value>text/html;charset=UTF-8</value>     
                </list>     
            </property>     
        </bean>      
    </mvc:message-converters>     
	</mvc:annotation-driven> 

	<!-- 对静态资源文件的访问 -->
	<mvc:default-servlet-handler />
	
<!-- 	<bean id="excel" class="com.oa.util.ExcelView"></bean> -->
	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="defaultContentType" value="application/json" />
		<property name="mediaTypes">
			<map>
				<entry key="html" value="application/x-www-form-urlencoded" />
				<entry key="json" value="application/json" />
				<entry key="xls" value="application/vnd.ms-excel" />
			</map>
		</property>
		<property name="viewResolvers">
			<list>
				<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
					<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
					<property name="prefix" value="/pages/" />
					<property name="suffix" value=".jsp" />
				</bean>
				<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
			</list>
		</property>
		<property name="defaultViews">
			<list>
				<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
			</list>
		</property>
	</bean>
</beans>


下面封装一个操作mongodb的操作类

@Resource
	private MongoTemplate mongoTemplate;
	
	List<T> list=null;
	
	@Override
	public List<T> getAllObject(Class<T> entity) {
		return mongoTemplate.findAll(entity);
	}

	@Override
	public boolean saveObject(T object) {
		mongoTemplate.insert(object);
		return true;
	}

	@Override
	public T getObject(Class<T> entity,String id) {
		return mongoTemplate.findById(id, entity);
	}

	@Override
	public WriteResult updataObject(Query query,Update update,Class<T> entity) {
		return mongoTemplate.updateFirst(query, update, entity);
	}

	@Override
	public WriteResult removeObject(Query query,Class<T> entity) {
		return mongoTemplate.remove(query, entity);
	}
	
	@Override
	public WriteResult removeObjectByEntity(T object,String collection){
		return mongoTemplate.remove(object, collection);
	}

	@Override
	public long getCount(Query query,String collection) {
		return mongoTemplate.count(query,collection);
	}

	@Override
	public void createCollection(Class<T> entity) {
		if (!mongoTemplate.collectionExists(entity)) {
			mongoTemplate.createCollection(entity);
		}
	}

	@Override
	public void dropCollection(Class<T> entity) {
		if (mongoTemplate.collectionExists(entity)) {
			mongoTemplate.dropCollection(entity);
		}
	}

	@Override
	public Map<Object,Object> getObjectByPage(int pages, int limit, Query query,
			Class<T> entity) {
		query.skip((pages-1)*limit);
		query.limit(limit);
		Map<Object, Object> map = new HashMap<Object, Object>();
		list = mongoTemplate.find(query, entity);
		int total =list.size();
		map.put("rows", list);
		map.put("total", total);
		return map;
	}

忘记有哪些需要删除的了,直接把现在的都贴上来,有些可能不合适,自行修改下即可

 类似资料: