用法解释
@ConditionalOnProperty(prefix = "server", name = "ssl.enabled", matchIfMissing = true, havingValue = "true")
prefix:application.yml文件中 配置(如配置文件)的名称
name:配置下面的属性名称,多级使用.点连接,如xxx.bbb.ccc
matchIfMissing:如果没有这个属性名,bean是否加载,默认是false(可以不用写),如果没有属性名就不加载bean
havingValue:判断属性名的值是否配备,如果匹配的话,bean才加载。
application.yml属性值
#服务器端口配置
server:
port: 8888 #正常访问https的端口
port-http: 2023 #这个是http端口,这个端口会做一个重定向的调整
ssl:
enabled: false #SSL证书是否启用
配置类TomcatConfig
package com.tj.config;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 配置http访问端口跳转到https端口的(非必须配置的)
*/
@Configuration
//根据ssl.enabled的值来控制是否加载,如果没有配置,就默认加载,如果配置了,当值为true的时候才加载
@ConditionalOnProperty(prefix = "server", name = "ssl.enabled", matchIfMissing = true, havingValue = "true")
public class TomcatConfig {
// http 请求端口,线上配置为 8080
@Value("${server.port-http}")
private int serverPortHttp;
// 服务器运行端口,等同于 HTTPS 请求端口,线上 443
@Value("${server.port}")
private int serverPortHttps;
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
// TODO Auto-generated method stub
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
factory.addAdditionalTomcatConnectors(createTomcatConnector());
return factory;
}
private Connector createTomcatConnector() {
Connector connector = new Connector(Http11NioProtocol.class.getName());
//Connector监听的http的端口号
connector.setPort(serverPortHttp);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(serverPortHttps);
return connector;
}
}