前几次的例子,要么是Shell,要么是普通Java应用程序的例子。
实际情况,是要在Spring的项目里用,因此需要做一些改造。
1.配置文件
C:\hanhai\config\mongodb.properties
mongodb.host=172.17.100.150
mongodb.port=27017
mongodb.db=zrb
2.配置文件对应的实体类
public class MongodbConfig {
private String host;
private String port;
private String db;
}
3.Spring扫描配置文件
<context:property-placeholder
location="file:${zhaorongbao.config_path}/config/mongodb.properties"
ignore-unresolvable="true" />
4.属性到实体类
<bean id="mongodbConfig" class="com.hanhai.zrb.api.mongodb.MongodbConfig">
<property name="host" value="${mongodb.host}"></property>
<property name="port" value="${mongodb.port}"></property>
<property name="db" value="${mongodb.db}"></property>
</bean>
5.Spring工具类,获得容器中的对象
需要扫描这个类SpringContextUtil
<context:component-scan base-package="com.hanhai.zrb.api.mongodb" />
SpringContextUtil在com.hanhai.zrb.api.mongodb这个包中。
@Component
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.ctx = applicationContext;
}
public static ApplicationContext getCtx(){
return ctx;
}
public static Object getBean(String name) throws BeansException {
return ctx.getBean(name);
}
}
6.SpringMVC中使用。
@
Controller
@RequestMapping("mongodb")
public class MongodbTestController extends BaseController {
@RequestMapping("test")
public void test(HttpServletResponse response) throws IOException {
DB db = MongoUtil.db();
ProjectDetail projectDetail = buildProjectDetail();
DBCollection projectDetailCollection = db
.getCollection("projectDetail");
}
7.MongoUtil工具类。
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import com.mongodb.DB;
import com.mongodb.Mongo;
public class MongoUtil {
public static final int DEFAULT_PORT = 27017;
public static final String DEFAULT_HOST = "172.17.100.150";
public static Logger log = Logger.getLogger(MongoUtil.class);
private static Mongo instance;
//@Resource(name="mongodbConfig")
//private static MongodbConfig mongodbConfig;
//没有直接注入
private static MongodbConfig config = null;
public static Mongo mongo() {
//使用工具方法获得容器中的对象
Object object=SpringContextUtil.getBean("mongodbConfig");
if(object instanceof MongodbConfig){
config = (MongodbConfig)object;
}else{
log.error("Mongodb config error~");
}
try {
if (instance == null) {
instance = new Mongo(config.getHost(), Integer.parseInt(config.getPort()));
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return instance;
}
public static DB db(){
Mongo mongo = MongoUtil.mongo();
DB db = mongo.getDB(config.getDb());
if(db == null){
throw new RuntimeException("Mongo db is null");
}
return db;
}
public static void close() {
if (instance != null) {
instance.close();
}
}
}