背景
旧项目中依然在使用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