Home Database Mysql Tutorial MongoDB:mongodb在spring项目中的配置

MongoDB:mongodb在spring项目中的配置

Jun 07, 2016 pm 03:22 PM
mongodb spring match project

最近在做基于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;
    }
Copy after login
粗体部分就是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>
Copy after login

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

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

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

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

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

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

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

How to choose a Java framework based on project needs How to choose a Java framework based on project needs Jun 05, 2024 pm 04:02 PM

Choosing the best Java framework based on project requirements requires: Determining project requirements (application type, number of users, required features, performance requirements) Researching available frameworks (e.g. Spring, SpringBoot, Hibernate, JakartaEE) Evaluating frameworks (feature set, user community, performance, ongoing support)

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

See all articles