我正在尝试如下设置trustStore和keyStore的系统属性:

@WebListener
public abstract class ContextListenerExample implements ServletContextListener {
    public void contextInitialized(ServletContextEvent e){
        System.setProperty("javax.net.ssl.trustStore", "C:\\Users\\trustCert.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "test123");
        System.setProperty("javax.net.ssl.trustStoreType", "jks");
        System.setProperty("javax.net.ssl.keyStore", "C:\\Users\\keyCert.p12");
        System.setProperty("javax.net.ssl.keyStorePassword", "keystore");
        System.setProperty("javax.net.ssl.keyStoreType", "keystoreType");
  }
}


我遵循示例here,但是当我运行应用程序时,它永远不会到达contextIntialized方法。另外,我不得不将ContextListenerExample类更改为抽象类。还有另一种设置系统属性的方法,还是我错过了一些需要修改的其他文件?

我添加了一个新文件SslConfiguration类:

@Configuration
public class SslConfiguration {
    @Value("${C:\\Users\\A21\\src\\main\\java\\org\\test\\certificates\\test.jks}")
    private Resource trustStore;

    @Value("test123")
    private String trustStorePassword;

    @Value("${C:\\Users\\A21\\src\\main\\java\\org\\test\\certificates\\test.p12}")
    private Resource keyStore;

    @Value("teststore")
    private String keyStorePassword;

    @Bean
    RestTemplate restTemplate() throws Exception {
        SSLContext sslContext = new SSLContextBuilder()
                .loadKeyMaterial(
                        keyStore.getFile(),
                        keyStorePassword.toCharArray(),
                        keyStorePassword.toCharArray())
                .loadTrustMaterial(
                        trustStore.getURL(),
                        trustStorePassword.toCharArray(),
                        // use this for self-signed certificates only:
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory socketFactory =
                new SSLConnectionSocketFactory(sslContext);
        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory).build();
        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }
}

最佳答案

抽象类无法实例化,因此这可能是从未调用此代码的原因。而不是使ContextListenerExample类抽象,请尝试实现在ServletContextListener接口中声明的另一个方法:

public void contextDestroyed(ServletContextEvent e) {
  // you can just leave it empty
}

08-18 00:02