How to inject Collection name in @Document from properties file in Spring Boot?

By | November 30, 2023

Sometimes in enterprise applications, we are required to configure the collection name from the properties file to our entity (model) class instead of hardcoding the collection name. In this tutorial, we will learn to inject Collection name in @Document from properties file.

Steps to inject Collection name in @Document from properties file

We are using a TaskManager Spring Boot application for this tutorial. To learn more about this application, please refer to CRUD Operations with Spring Boot and MonogDB.

Step 1- Create a Configuration class

We need a configuration class and a variable that will be used to read the data from the properties ( or application.yaml) file.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

 * @Value- Used to assign the value of expression to the annotated variable
 * @author paulsofts

public class MongoConfig {
	private String collectionName;
	public String getCollectionName() {
		return collectionName;

Step 2- Configure application.yaml file

Below, we can see we have configured the collection name in our file.

Step 3- Pass collection name to Model class

Now, we will consume the collection name in our model (entity) class. In order to do this, we use the following command:

@Document(collection = "#{@mongoConfig.collectionName}")

As our MongoConfig class is annotated with the @Configuration annotation, we can refer to its bean with the help of @mongoConfig (The bean names are in lowercase and follow a camelcase structure). Below, we have the complete model class for reference.

import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Document(collection = "#{@mongoConfig.collectionName}")
public class Task {
	private int taskId;
	@Field(name="Task Importance")
	private long taskSeverity;
	private String taskName;
	private String taskAssignee;
	private Date date;


Leave a Reply

Your email address will not be published. Required fields are marked *