在我的代码下面,返回值为null。
ConfigurationFile.java
package config;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import com.mongodb.MongoClient;
@Configuration
public class ConfigurationFile {
private static MongoTemplate mongoTemplate;
public @Bean(name="mongoTemplate")
MongoTemplate mongoTemplate()throws Exception{
mongoTemplate = new MongoTemplate(new MongoClient("localhost",27017),"Test");
System.out.println("mongoTemplateValue1--> " + mongoTemplate);
return mongoTemplate;
}
public static MongoTemplate getMongoTemplate() {
System.out.println("mongoTemplateValue-->" + mongoTemplate);
return mongoTemplate;
}
}
Client.java
package client;
import java.net.UnknownHostException;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import config.ConfigurationFile;
import extraction.Extractor;
public class Client {
private MongoTemplate mongoTemplate;
public static void main(String[] args){
Client c = new Client();
c.sample();
}
private void sample(){
SetupMongoDb();
}
private void SetupMongoDb() {
if (mongoTemplate == null) {
System.out.println("insideSetup");
mongoTemplate = ConfigurationFile.getMongoTemplate();
}
}
}
我无法获取mongoTemplate值。输出下方 insideSetup mongoTemplateValue - >空
有人可以帮忙吗?
答案 0 :(得分:0)
您的mongoTemplate()
方法永远不会被调用,因为在使用Client.main()
启动应用程序时,您实际上并未创建Spring Context。
需要了解Spring Framework的工作原理,特别是如何create application context。然后,您需要将上下文指向配置文件,并使用自动装配获取MongoTemplate
。
@Configuration
public class ConfigurationFile {
@Bean(name="mongoTemplate")
public MongoTemplate mongoTemplate()throws Exception{
MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient("localhost",27017),"Test");
return mongoTemplate;
}
}
然后只使用自动连接字段:
@Service
public class SomeService {
@Autowired
private MongoTemplate mongoTemplate;
public doSomething() {
//Use your mongoTemplate
}
}