我使用的是Spring-Boot项目和MongoRepository而不是MongoTemplate。如何使用MongoRepository动态设置主机名
当使用MongoTemplate,一个可以动态使用MongoConnectionPool像这样设置主机名:
@Autowired
MongoConnectionPool mongoConn
....
mongoConn.setHostname("127.23.45.89");
mongoConn.setPort(27017);
如何实现使用MongoRepository同样的效果?
我知道,我可以通过在application.properties文件中指定
spring.data.mongodb.host=hostname1
spring.data.mongodb.port=27017
指定的主机名和端口。
但是我使用GenericContainer通过Docker容器启动一个mongo实例来运行我的单元测试。容器将动态IP地址和端口分配给mongo实例,因此我需要能够在运行时动态设置MongoRepository的主机名和端口。
这是我如何设置我的单元测试。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MongoConfiguration.class)
public class HierarchiesServiceImplTests {
private static final Logger log = LoggerFactory.getLogger(HierarchiesServiceImplTests.class);
@Autowired
private HierarchiesService hierarchiesService;
@Autowired
private HierarchyRepository hierarchyRepo;
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
startMongo();
}
/**
* Starts a Mongo docker container, and configures the repository factory to use this instance.
*/
private void startMongo() {
GenericContainer mongo = new GenericContainer("mongo:3")
.withExposedPorts(27017);
mongo.start();
String containerIpAddress = mongo.getContainerIpAddress();
int mappedPort = mongo.getMappedPort(27017);
//TODO: set the hostname and port here so that the MongoRepository use this mongo instance instead of the default localhost.
log.info("Container mongo:3 listening on {}:{}", containerIpAddress, mappedPort);
}
这是我在我的MongoConfiguration.class
@Configuration
@EnableMongoRepositories
@ComponentScan({"com.is.hierarchies.service"})
public class MongoConfiguration {
}
@Alex,谢谢你的建议。标签“弹簧”更改为“弹簧启动” – Antwan
我已经添加了另一个答案,我相信这更符合您寻找的内容 – alexbt