我的應用程式使用 spring-boot 2.5.5。
我在應用程式啟動時為 Tomcat 設定了一個屬性,以允許編碼斜線@PathVariable:
@SpringBootApplication
public class App {
public static void main(String[] args) {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
SpringApplication.run(App.class, args);
}
}
當我啟動應用程式時,一切正常,除了在我的集成測驗中:
@ActiveProfiles("test-connected")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension.class)
class GlobalFullTest {
當我除錯org.apache.tomcat.util.buf.UDecoder類時:我看到屬性org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH是null加載類時,所以false設定了默認值。
我嘗試了以下方法:
- 添加我
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");的@BeforeAll測驗方法 properties = { "org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true" }在@SpringBootTest注釋中添加。- 添加
org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH: true在我的application-test-connected.yaml - 使用
WebServerFactoryCustomizer:
@Configuration
public class WebServerConfiguration {
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return factory -> factory.addConnectorCustomizers(connector -> connector.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"));
}
}
但是這些都不起作用:當按org.apache.tomcat.util.buf.UDecoder 類檢索屬性時,它的值總是null.
org.apache.tomcat.util.buf.UDecoder在加載類之前如何設定屬性?
uj5u.com熱心網友回復:
參考如何在 spring 測驗中設定環境變數或系統屬性?
最簡單的方法
按照在類中添加靜態初始化程式
...
class GlobalFullTest {
static {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
}
...
}
down side is we need to copy that for every test.
清潔方式
創建 ApplicationContextInitializer,它可以在 Spring 應用程式和任何其他測驗中重用。
public class CustomApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
}
}
...
@ContextConfiguration(initializers = CustomApplicationContextInitializer.class,...)
class GlobalFullTest {
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/511504.html
