title: how to specify database name in spring data mongoDB
body: <p>I am using Mongo repositories to perform CRUD operations as in the code below. Although this code works, but the documents and collections are created in a different DB than the one that I want. How can I explicitly specify a DB name to which documents will be stored.</p>
  
  <p>The POJO class:</p>
  
  <pre><code>@Document(collection = "actors")
  public class Actor 
  {
    @Id
    private String id;
    ...
    //constructor
    //setters &amp; getters
  }
  </code></pre>
  
  <p>The repository:</p>
  
  <pre><code>public interface ActorRepository extends MongoRepository&lt;Actor, String&gt; 
  {
    public Actor findByFNameAndLName(String fName, String lName);
    public Actor findByFName (String fName);
    public Actor findByLName(String lName);
  }
  </code></pre>
  
  <p>The service that uses the repository:</p>
  
  <pre><code>@Service
  public class ActorService 
  {
    @Autowired
    private ActorRepository actorRepository;
  
    public Actor insert(Actor a)
    {
      a.setId(null);
      return actorRepository.save(a);
    }
  } 
  </code></pre>
  
  <p>And I access the service from a REST controller class:</p>
  
  <pre><code>@RestController
  public class Controllers 
  {
  
    private static final Logger logger = Logger.getLogger(Controllers.class);
    private static final ApplicationContext ctx = new  AnnotationConfigApplicationContext(SpringMongoConfig.class);
  
    @Autowire
    private ActorService actorService;
  
    @RequestMapping(value="/createActor", method=RequestMethod.POST)
    public @ResponseBody String createActor(@RequestParam(value = "fName") String fName,
          @RequestParam(value = "lName") String lName,
          @RequestParam(value = "role") String role)
    {
      return actorService.insert(new Actor(null,fName,lName,role)).toString();
  
    }
  
   ...
  }
  </code></pre>
  
  <p>I have created this spring mongoDB configuration class which has the option of setting DB name, but could not figure out how to use it with the repositories above.</p>
  
  <pre><code>@Configuration
  public class SpringMongoConfig extends AbstractMongoConfiguration
  { 
      @Bean
      public GridFsTemplate gridFsTemplate() throws Exception 
      {
          return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
      }
  
      @Override
      protected String getDatabaseName() 
      {
          return "MyDB";
      }
  
      @Override
      @Bean
      public Mongo mongo() throws Exception 
      {
          return new MongoClient("localhost" , 27017 );
      }
  
      public @Bean MongoTemplate mongoTemplate() throws Exception 
      {
          return new MongoTemplate(mongo(), getDatabaseName());
      }    
  }
  </code></pre>