另外一个普遍的情况是在应用中会有两份个HTTP端口连接,一个是HTTP,另外一个是HTTPS。
3.5.1准备工作
为了创建HTTPS的连接,我们需要创建在自己的电脑上创建证书,这个证书可以加密和解密在SSL的交流过程中。
如果你是Unix或Mac,执行以下命令创建证书:$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
如果你是windows,那么,先进入jdk安装的路径,即JAVA_HOME的bin目录下,然后执行以下的命令:keytool -genkey -alias tomcat -keyalg RSA。
执行命令后,你还要输入信息,根据提示来填写。不过我们密码就设置为changeit,当然你也可以自己定义。都填写好了之后,你可以在C:\Users\*目录下看到名称为.keystore的文件。
3.5.2代码实现
keystore创建之后,我们需要创建配置文件为了给HTTPS的连接器,例如端口或其它的。之后, 我们将会创建配置属性连接对象和使用它到我们新的连接器中。具体步骤如下:
- 首先,我们创建tomcat.https.properties文件在src/main/resources目录下。
|
custom.tomcat.https.port=8443 |
2.接着,我们创建静态的类,名称为TomcatSslConnectorProperties在我们的WebConfiguration类中。
|
@ConfigurationProperties(prefix = "custom.tomcat.https") |
3.现在我们需要将我们的tomcat.http.properties文件作为Spring Boot的属性资源,而且与TomcatSslConnectorProperties相结合。
|
@Configuration |
4.最后,我们需要在WebConfiguration中创建EmbeddedServletContainerFactor作为Spring 的bean,这个类将会添加HTTPS作为连接器。
|
@Bean private Connector createSslConnector(TomcatSslConnectorProperties
|
注意,Spring Boot2.x以上的版本servletContainer这个方法应该如下写:
|
// springboot2 写法 @Bean public TomcatServletWebServerFactory servletContainer(TomcatSslConnectorProperties properties) { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addAdditionalTomcatConnectors(createSslConnector(properties)); return tomcat; } |
5.启动程序,访问地址:https://localhost:8443/internal/tomcat.https.properties,你将会看到。
3.5.3代码说明
这代码中,我们创建了tomcat.https.properties和TomcatSslConnectorProperties,并将二者结合起来。读者可以看到,TomcatSslConnectorProperties中的参数都在tomcat.https.rpoperties中已经定义好了。
@ConfigurationProperties(prefix=”custom.tomcat.https”)在方法TomcatSslConnectorProperties上注释是个重要的地方。它告诉Spring Boot自动去装配前缀为custom.tomcat.https的属性,这些属性的字段也声明在TomcatSslConnectorProperties中,而且这些属性在灶中还要声明getter和setter的方法。同时,Spring 在装配时,还要自动去配置参数的类型。例如,custom.tomcat.https.keystore会自动匹配为File的作用对象。(这样的转换也可以用于我们自定义的属性类型。)
我们声明一系列的参数在tomcat.https.properties文件中告诉Spring Boot去载入这些参数。这个过程是通过我们加入了这行代码@PropertySource(“classpath:/tomcat.https.properties”)在WebConfiguration类上面。@EnableConfigurationProperties(WebConfiguration.TomcatSslConnectorProperties.class)这行代码告诉Spring Boot自动创建TomcatSslConnectorProperties实例来使用。
我们创建EmbeddedServletContainerFactory的bean提供给Spring Boot的bean工厂去创建EmbeddedServletContainer,方便configureConnector(Connector connector)方法去封装放入属性值。