Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to do the following in a Dropwizard app:
public void run(SandmanConfiguration configuration, Environment environment) {
MongoClient mongoClient = configuration.getMongoFactory().build(environment);
environment.lifecycle().manage(mongoClient);
This references the MongoFactory's build method:
public MongoClient build(Environment environment) {
// Example conn string: "mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test"
MongoClient mongoClient = new MongoClient(getHost(), getPort());
environment.lifecycle().manage(new Managed() {
@Override
public void start() {
@Override
public void stop() {
LOGGER.info("Mongo Client is being shut down...");
mongoClient.close();
return mongoClient;
How ever when i try to use mongoClient this way I get an error:
environment.lifecycle().manage(mongoClient);
Cannot resolve method 'manage(com.mongodb.MongoClient)
–
I just figured out that the best is to create a separate call that implements start and stop for the mongo client.
import com.mongodb.MongoClient;
import io.dropwizard.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MongoClientManager implements Managed {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoClientManager.class);
private final MongoClient client;
public MongoClientManager(MongoClient client) {
this.client = client;
@Override
public void start() throws Exception {
LOGGER.info("MongoClient is starting up...");
@Override
public void stop() throws Exception {
LOGGER.info("MongoClient is being shut down...");
client.close();
This way I can safely shut down the client when the app is stopping.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.