Spring Boot MongoDB Integration: Defining MongoTemplate Bean
To define a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' in your configuration, follow these steps:
- Add Dependencies: Include the required dependencies in your project's build file (e.g., pom.xml for Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- Create Configuration Class: Create a configuration class (e.g., MongoConfig) and annotate it with
@Configuration:
@Configuration
public class MongoConfig {
@Autowired
private MongoProperties mongoProperties;
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoClient mongoClient = new MongoClient(mongoProperties.getHost(), mongoProperties.getPort());
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, mongoProperties.getDatabase());
return mongoTemplate;
}
}
- Configure Properties: Provide the necessary properties in your application.properties or application.yml file:
spring.data.mongodb.host=your_host
spring.data.mongodb.port=your_port
spring.data.mongodb.database=your_database
- Autowire and Use: Autowire the MongoTemplate bean in your application classes:
@Autowired
private MongoTemplate mongoTemplate;
You can now use the MongoTemplate instance to perform operations on your MongoDB database.
原文地址: https://www.cveoy.top/t/topic/lJ3G 著作权归作者所有。请勿转载和采集!