MongoDB在spring中xml传统配置

背景

旧项目中依然在使用springmvc的xml传统配置,最近需要使用MongoDB,需要在spring引入MongoDB的连接配置。

解决

配置mongodb数据库

<?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.0.xsd">

    <!-- Default bean name is 'mongo' -->
    <mongo:mongo-client id="mongoClient" host="localhost" port="27017"/>

</beans>

配置mongodb数据工厂

<mongo:db-factory id="mongoDbFactory" mongo-ref="mongoClient"/>

配置mongodb的Template

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
	<constructor-arg ref="mongoDbFactory"/>
</bean>

配置mongodb的dao文件夹位置

<mongo:repositories base-package="com.xxx.dao" mongo-template-ref="mongoTemplate" />

mongodb的dao实现

package com.xxx.dao;

import com.xxx.model.Form;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface FormRepository extends MongoRepository<Form, String>{

public List<Form> findByCreator(String creator);
}

mongodb的service实现

package com.xxx.service;

import com.xxx.dao.FormRepository;
import com.xxx.model.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value = "formService")
public class FormService {

	@Autowired
	FormRepository formRepository;

	/**
	 * 根据创建者,获取表单
	 * @param creator 创建者
	 * @return 表单列表
	 */
	public List<Form> findByCreator(String creator){
		return formRepository.findByCreator(creator);
	}
}

感受

如果使用spring boot的配置文件配置的这个方式,是最好的。能不用xml配置就不用,毕竟官方首先教我们都是去xml化配置的。

参考: Introduction to Spring Data MongoDB Spring Data MongoDB - Reference Documentation

转载于:https://my.oschina.net/fxtxz2/blog/1828908

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值