찾다
데이터 베이스MySQL 튜토리얼MongoDB:mongodb在spring项目中的配置

最近在做基于mongodb的spring项目架构,有个问题跟大家分享一下,也方便自己以后能够用到 先看一个简单的项目架构: 在架构方面唯一需要说的是采用的是spring的注解: 下面是部分代码,部分。 /** * @author jessonlv * 用户注册接口 */ @Controller@Request

最近在做基于mongodb的spring项目架构,有个问题跟大家分享一下,也方便自己以后能够用到

先看一个简单的项目架构:

\

在架构方面唯一需要说的是采用的是spring的注解:

下面是部分代码,部分。

/**
 * @author jessonlv
 * 用户注册接口
 */
<strong>@Controller
@RequestMapping("/user")</strong>  
public class UserInfoController {
	@Autowired
	private UserInfoManager userManager;
	//接口文档
	<strong>@RequestMapping(method=RequestMethod.GET)</strong>
	public String list(HttpServletRequest request,HttpServletResponse response){
		 response.setContentType("text/html;charset=utf-8");  
		return "user";
	}
	//检测用户信息-根据帐户
	<strong>@RequestMapping(value="/check",method=RequestMethod.GET)
</strong>    public String getUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//设置HTTP头 
		 response.setContentType("text/html;charset=utf-8");  
		 //参数获取
		 String account=StringUtil.formatStringParameter(request.getParameter("account"), null);
		 String key=StringUtil.formatStringParameter(request.getParameter("key"), null);//验证调用方
		 //参数有效性验证
		 if(account==null){
			 throw new ParameterException();
		 }
		 //TODO:key验证
		 
		 //查询对象
		 BasicDBObject o=new BasicDBObject("account",account);
		 try {
			//取数据库
			DBObject doc=userManager.getUserInfo(o);
			//输出结果
			PrintWriter writer=response.getWriter();
			writer.write(doc.toString());
		} catch (Exception e) {
			e.printStackTrace();
			//输出结果
			PrintWriter writer=response.getWriter();
			writer.write(new BasicDBObject().toString());
		}
		//db.find(query).skip(pos).limit(pagesize)分页
		return null;
    }
粗体部分就是spring的注解。我们得到的接口调用是这个样子的:http://localhost/ucenter/user/check?account=11&pwd=11111 注意是get请求。

采用mongodb的最大好处中的其中一个就是不用写bean,只需做一些简单的配置

我们看spring-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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"  
	xmlns:cache="http://www.springframework.org/schema/cache" xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tool="http://www.springframework.org/schema/tool"
	xsi:schemaLocation=" 
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
	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/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
	http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool-3.1.xsd
	http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd" 
	default-autowire="byName" default-lazy-init="true">
	<context:annotation-config />
	<context:component-scan base-package="com.ishowchina.user" />
	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="/" p:suffix=".html" />
    <bean id="multipartResolver"  
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
          p:defaultEncoding="utf-8" />   
    <!-- 支持json    --> 
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>  
            </list>  
        </property>  
    </bean>
    <!-- 导入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <list>  
                <value>classpath:appconfig.properties</value>
            </list>  
        </property>  
    </bean>
    <!-- 数据源 -->
    <bean id="dataSource" class="com.ishowchina.user.dao.DataSource">
    	<property name="ip" value="localhost"/> 
    	<property name="port" value="27017"/> 
    </bean>
    <bean id="userDao" class="com.ishowchina.user.dao.impl.UserInfoDaoImpl">
    	<property name="dbName" value="prop"/> 
    	<property name="tableName" value="userinfo"/>
    	<property name="dataSource" ref="dataSource"/> 
    </bean>
    <bean id="stationDao" class="com.ishowchina.user.dao.impl.StationInfoDaoImpl">
    	<property name="dbName" value="prop"/> 
    	<property name="tableName" value="stationinfo"/>
    	<property name="dataSource" ref="dataSource"/> 
    </bean>
</beans>

上面的都是些常规的配置,最重要的就是数据源部分

//数据源地址
//端口号

//数据库名
//对应的表明

道理其实还是和bean是一样的,这在项目启动的前期都已经映射了。每写一个dao就配置一个....,剩了很多的事儿,而且刚开始的有些不习惯。但是效率挺高,结构清晰。

接口的输出结果也很简单:DBObject myDocDbObject = userManager.getUserInfo(repeatAccount);

String str = myDocDbObject.toString(); 是一个json格式的字符。

呵呵,做个小总结,方便忘记了。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
mongodb php 扩展没有怎么办mongodb php 扩展没有怎么办Nov 06, 2022 am 09:10 AM

mongodb php扩展没有的解决办法:1、在linux中执行“$ sudo pecl install mongo”命令来安装MongoDB的PHP扩展驱动;2、在window中,下载php mongodb驱动二进制包,然后在“php.ini”文件中配置“extension=php_mongo.dll”即可。

Redis和MongoDB的区别与使用场景Redis和MongoDB的区别与使用场景May 11, 2023 am 08:22 AM

Redis和MongoDB都是流行的开源NoSQL数据库,但它们的设计理念和使用场景有所不同。本文将重点介绍Redis和MongoDB的区别和使用场景。Redis和MongoDB简介Redis是一个高性能的数据存储系统,常被用作缓存和消息中间件。Redis以内存为主要存储介质,但它也支持将数据持久化到磁盘上。Redis是一款键值数据库,它支持多种数据结构(例

Go语言中使用MongoDB:完整指南Go语言中使用MongoDB:完整指南Jun 17, 2023 pm 06:14 PM

MongoDB是一种高性能、开源、文档型的NoSQL数据库,被广泛应用于Web应用、大数据以及云计算领域。而Go语言则是一种快速、开发效率高、代码可维护性强的编程语言。本文将为您完整介绍如何在Go语言中使用MongoDB。一、安装MongoDB在使用MongoDB之前,需要先在您的系统中安装MongoDB。在Linux系统下,可以通过如下命令安装:sudo

php7.0怎么安装mongo扩展php7.0怎么安装mongo扩展Nov 21, 2022 am 10:25 AM

php7.0安装mongo扩展的方法:1、创建mongodb用户组和用户;2、下载mongodb源码包,并将源码包放到“/usr/local/src/”目录下;3、进入“src/”目录;4、解压源码包;5、创建mongodb文件目录;6、将文件复制到“mongodb/”目录;7、创建mongodb配置文件并修改配置即可。

php怎么使用mongodb进行增删查改操作php怎么使用mongodb进行增删查改操作Mar 28, 2023 pm 03:00 PM

MongoDB作为一款流行的NoSQL数据库,已经被广泛应用于各种大型Web应用和企业级应用中。而PHP语言也作为一种流行的Web编程语言,与MongoDB的结合也变得越来越重要。在本文中,我们将会学习如何使用PHP语言操作MongoDB数据库进行增删查改的操作。

SpringBoot中logback日志怎么保存到mongoDBSpringBoot中logback日志怎么保存到mongoDBMay 18, 2023 pm 07:01 PM

自定义Appender非常简单,继承一下AppenderBase类即可。可以看到有个AppenderBase,有个UnsynchronizedAppenderBase,还有个AsyncAppenderBase继承了UnsynchronizedAppenderBase。从名字就能看出来区别,异步的、普通的、不加锁的。我们定义一个MongoDBAppender继承UnsynchronizedAppenderBasepublicclassMongoDBAppenderextendsUnsynchron

SpringBoot怎么整合Mongodb实现增删查改SpringBoot怎么整合Mongodb实现增删查改May 13, 2023 pm 02:07 PM

一、什么是MongoDBMongoDB与我们之前熟知的关系型数据库(MySQL、Oracle)不同,MongoDB是一个文档数据库,它具有所需的可伸缩性和灵活性,以及所需的查询和索引。MongoDB将数据存储在灵活的、类似JSON的文档中,这意味着文档的字段可能因文档而异,数据结构也会随着时间的推移而改变。文档模型映射到应用程序代码中的对象,使数据易于处理。MongoDB是一个以分布式数据库为核心的数据库,因此高可用性、横向扩展和地理分布是内置的,并且易于使用。况且,MongoDB是免费的,开源

PHP实现MongoDB数据库可用性的方法PHP实现MongoDB数据库可用性的方法May 16, 2023 am 10:01 AM

随着互联网技术的不断发展,大数据成为企业发展的重要资产。而对于企业来说,数据的可用性和安全性至关重要。MongoDB是一个高性能、高可用性的NoSQL数据库,越来越受到企业的青睐。然而,MongoDB的可用性也是企业关注的焦点之一,本文将介绍PHP实现MongoDB数据库可用性的方法。一、了解MongoDB的高可用性特性MongoDB作为NoSQL数据库,具

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구