@Configuration
class SpringMongoConfig {
@Value("\${spring.data.mongodb.host}")
private val host: String? = null
@Value("\${spring.data.mongodb.port}")
private val port: Int? = 27017
@Value("\${spring.data.mongodb.database}")
private val database: String? = "database"
@Bean
fun mongoTemplate(): MongoTemplate {
val options = MongoClientOptions.Builder().socketKeepAlive(true).build()
val factory = SimpleMongoDbFactory(MongoClient(ServerAddress(host!!, port!!), options), database)
//remove _class
val converter = MappingMongoConverter(factory, MongoMappingContext())
converter.typeMapper = DefaultMongoTypeMapper(null)
return MongoTemplate(factory, converter)
}
}
application.yml:
---
spring:
profiles: dev
data:
mongodb:
host: localhost
port: 27017
database: database
多个数据库:
@Configuration
class MongoConfig {
@Value("\${spring.data.mongodb.host}")
private val host: String? = null
@Value("\${spring.data.mongodb.port}")
private val port: Int? = 27017
@Value("\${spring.data.mongodb.database}")
private val maker = "maker"
@Value("\${spring.data.mongodb1.host}")
private val host1: String? = null
@Value("\${spring.data.mongodb1.port}")
private val port1: Int? = 27017
@Value("\${spring.data.mongodb1.database}")
private val maker2 = "maker"
@Bean
fun makerTemplate(): MongoTemplate {
val factory = SimpleMongoDbFactory(MongoClient(host!!, port!!), maker)
//remove _class
val converter = MappingMongoConverter(factory, MongoMappingContext())
converter.setTypeMapper(DefaultMongoTypeMapper(null))
return MongoTemplate(factory, converter)
}
@Bean
@Primary
fun maker2Template(): MongoTemplate {
val factory = SimpleMongoDbFactory(MongoClient(host1!!, port1!!), maker2)
//remove _class
val converter = MappingMongoConverter(factory, MongoMappingContext())
converter.setTypeMapper(DefaultMongoTypeMapper(null))
return MongoTemplate(factory, converter)
}
}
配置文件:
---
spring:
profiles: product
data:
mongodb:
host: mongo
port: 27017
database: maker
mongodb1:
host: mongo
port: 27017
database: maker2
用法:
@RestController
@RequestMapping("/")
class ReportController {
@Autowired
@Qualifier("makerTemplate")
private lateinit var makerTemplate: MongoTemplate
@Autowired
@Qualifier("maker2Template")
private lateinit var maker2Template: MongoTemplate
...
}