舊項目中依然在使用springmvc的xml傳統配置,最近須要使用MongoDB,須要在spring引入MongoDB的鏈接配置。html
<?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>
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongoClient"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory"/> </bean>
<mongo:repositories base-package="com.xxx.dao" mongo-template-ref="mongoTemplate" />
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); }
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化配置的。java
參考: Introduction to Spring Data MongoDB Spring Data MongoDB - Reference Documentationspring