java - mongoDB connection returning null value -
below code returning value 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(); } } } i unable mongotemplate value. below output insidesetup mongotemplatevalue-->null
can please on this?
your mongotemplate() method never being called because not creating spring context when starting application client.main(). need learn how spring framework works, how create application context. you'll need point context configuration file , use autowiring obtain mongotemplate.
@configuration public class configurationfile { @bean(name="mongotemplate") public mongotemplate mongotemplate()throws exception{ mongotemplate mongotemplate = new mongotemplate(new mongoclient("localhost",27017),"test"); return mongotemplate; } } then use autowired field:
@service public class someservice { @autowired private mongotemplate mongotemplate; public dosomething() { //use mongotemplate } }
Comments
Post a Comment