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 (application.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
*/
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.collection}")
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 application.properties file.
server.port=9090
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=task_db
spring.data.mongodb.collection=tasks
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 org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Document(collection = "#{@mongoConfig.collectionName}")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Task {
@Id
private int taskId;
@Field(name="Task Importance")
private long taskSeverity;
private String taskName;
private String taskAssignee;
@Field(name="Date")
private Date date;
}