packageorg.xftm.app;importorg.apache.catalina.Context;importorg.apache.catalina.connector.Connector;importorg.apache.tomcat.util.descriptor.web.SecurityCollection;importorg.apache.tomcat.util.descriptor.web.SecurityConstraint;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.Banner;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.embedded.EmbeddedServletContainerFactory;importorg.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;importorg.springframework.boot.web.client.RestTemplateBuilder;importorg.springframework.context.annotation.Bean;importorg.springframework.web.client.RestTemplate;importspringfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2//Swaggerapi集成,入不需要可直接删除public classApplication {
@Value("${server.httpPort}")privateString httpPort;//在yml文件中自定义的http端口
@Value("${server.httpsPort}")privateString httpsPort; //在yml文件中自定义https端口
@Autowired
RestTemplateBuilder restTemplateBuilider;public static voidmain(String[] args) {
SpringApplication application= new SpringApplication(Application.class);
application.setBannerMode(Banner.Mode.CONSOLE);//笔者自定义的banner 此处可按照Springboot默认启动方式启动
application.run(args);
}
@BeanpublicEmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat= newTomcatEmbeddedServletContainerFactory() {
@Overrideprotected voidpostProcessContext(Context context) {
SecurityConstraint constraint= newSecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection= newSecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());returntomcat;
}
@BeanpublicConnector httpConnector() {
Connector connector= new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
System.out.println("httpport="+httpPort);
System.out.println("httpsPort="+httpsPort);//Connector监听的http的端口号
connector.setPort(httpPort ==null?8080:Integer.valueOf(httpPort));
connector.setSecure(false);//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(httpsPort ==null?443:Integer.valueOf(httpPort));returnconnector;
}
@BeanpublicRestTemplate restTemplate() {//使用build()方法进行获取
returnrestTemplateBuilider.build();
}
}