![](/img/trans.png)
[英]Spring boot with @RefreshScope @PostConstruct @PreDestroy
[英]Spring issue with @PostConstruct and @PreDestroy
我有一個 Spring 應用程序,我正在嘗試使用 EmbededRedis 進行測試。 所以我創建了一個像下面這樣的組件來初始化並在測試后殺死 redis。
@Component
public class EmbededRedis {
@Value("${spring.redis.port}")
private int redisPort;
private RedisServer redisServer;
@PostConstruct
public void startRedis() throws IOException {
redisServer = new RedisServer(redisPort);
redisServer.start();
}
@PreDestroy
public void stopRedis() {
redisServer.stop();
}
}
但現在我面臨一個奇怪的問題。 因為 spring 緩存了上下文,所以在我的測試執行后每次都不會調用 PreDestroy,但是由於某種原因,@PostConstruct 被調用,並且 EmbededRedis 試圖一次又一次地啟動正在運行的 redis 服務器,這是執行過程中的問題。
有沒有辦法以任何方式處理這種情況?
更新這就是我主要定義我的測試的方式。
@SpringBootTest(classes = {SpringApplication.class})
@ActiveProfiles("test")
public class RedisApplicationTest {
拋棄 class 並編寫一個@Configuration
class 將RedisServer
暴露為一個 bean。
@Configuration
public void EmbeddedRedisConfiguration {
@Bean(initMethod="start", destroyMethod="stop")
public RedisServer embeddedRedisServer(@Value("${spring.redis.port}") int port) {
return new RedisServer(port);
}
}
所以我按照@M 的建議調試了 ContextInitialization。 迪南。
對我來說,問題是,我們的應用程序是 mocking 不同的類,以便將 mocking 與 Spring 上下文混合。 現在,當您使用模擬時, MockitoContextInitializer
也會成為您緩存鍵的一部分,這會導致緩存未命中。 原因是,對於不同的測試類,mock 下的類明顯不同。
看情況,我更喜歡 go 在測試完成后使用@DirtiesContext
使比賽無效,以便稍后我可以重新初始化上下文以進行不同的測試。
注意@DirtiesContext
建議避免使用,因為它會減慢測試速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.