2018-6-30

Java

Spring Boot with knife4j Spring Boot with MyBatis Spring Boot with Thymeleaf Spring Boot with Web Socket

MyBatis with Springboot

Spring

Spring Boot (Holle Word)


简介

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

Spring Boot 是由 Pivotal 团队提供的全新框架, 其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程; 该框架使用了特定的方式来进行配置, 从而使开发人员不再需要定义样板化的配置;

注意版本支持: Spring Boot 2.0.3.RELEASE requires Java 8 or 9 and Spring Framework 5.0.7.RELEASE

官方主页 项目生成器 文档主页

纯 maven 组建

  1. SpringBoot for maven 参考: 10.1.1 Maven Installation

找个目录创建 pom.xml
内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.example</groupId>
        <artifactId>myproject</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <!-- 继承parent 默认的配置-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.3.RELEASE</version>
        </parent>
        <!-- Additional lines to be added here... -->
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    </project>

没问题的话执行mvn dependency:tree会看到 BUILD SUCCESS

  1. 代码

参考: 11.3 Writing the Code

创建src/main/java/Example.java
内容如下:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
 
@RestController
@EnableAutoConfiguration
public class Example {
 
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
 
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }
 
}

代码解释看: 11.3.1 The @RestController and @RequestMapping Annotations

  1. Start Running!

执行 mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
    :: Spring Boot ::       (v2.0.3.RELEASE)

Eclipse 的 maven Springboot

  1. 新建Maven项目 即: 一般的java项目maven-archetype-quickstart x.x

  2. 修改pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
 
<groupId>myproject</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
 
<name>springboot</name>
<url>http://maven.apache.org</url>
 
<!-- 这官方示例的项目名
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
-->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>
 
    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
 
    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
 
  1. Run As Maven Install

指定项目jdk版本
<plugins>元素增加

<!-- 指定jdk --> 
<plugin> 
	<groupId>org.apache.maven.plugins</groupId> 
	<artifactId>maven-compiler-plugin</artifactId> 
	<configuration> 
	<source>1.8</source> 
	<target>1.8</target> 
	</configuration> 
</plugin> 

关于 各种cannot be read or is not a valid错误, Maven下载包损坏了,删掉重下 关于 [ERROR] /F:/test/src/main/java/Example.java:[1,1] 程序包org.springframework.boot不存在的错误(换JDK8,包括maven,项目依赖,系统环境) 也是组建完了,运行Example:main没有挂起; 内置tomcat没有启动(Unregistering JMX-exposed beans on shutdown)

  1. 踩坑补充

http://start.spring.io 下载到web项目pom.xml配置合并后,完整配置:

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>myproject</groupId>  
  <artifactId>springboot</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <packaging>jar</packaging>  
  <name>springboot</name>  
 
  <parent> 
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-parent</artifactId>  
    <version>2.0.3.RELEASE</version>  
    <relativePath/>  
    <!-- lookup parent from repository --> 
  </parent> 
 
  <properties> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
    <java.version>1.8</java.version> 
  </properties>  
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-web</artifactId> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-starter-test</artifactId>  
      <scope>test</scope> 
    </dependency> 
  </dependencies>  
  <build> 
    <plugins> 
      <plugin> 
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin>  
      <!-- 指定jdk -->  
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId>  
        <artifactId>maven-compiler-plugin</artifactId>  
        <configuration> 
          <source>1.8</source>  
          <target>1.8</target> 
        </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project>
 

仍然有 (Unregistering JMX-exposed beans on shutdown)的问题, 最后是包损坏的问题, 整个Maven仓库删掉全部重新下载

运行Example::main OK!!!

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
:: Spring Boot ::       (v2.0.3.RELEASE)

(yeah~)

spring starter

大概是整合多框架的库, 一个大模块**(官称为:starter)** 例如: spring-boot-starter-web的maven依赖, 它包括Spring MVC , RESTful 和内嵌 tomcat作为默认的容器..

参考: 13.5 Starters

下表列出1.3版本的部分starter:

名称描述
spring-boot-starter核心Spring Boot starter, 包括自动配置支持, 日志和YAML
spring-boot-starter-actuator生产准备的特性, 用于帮你监控和管理应用
spring-boot-starter-amqp对”高级消息队列协议”的支持, 通过spring-rabbit实现
spring-boot-starter-aop对面向切面编程的支持, 包括spring-aop和AspectJ
spring-boot-starter-batch对Spring Batch的支持, 包括HSQLDB数据库
spring-boot-starter-data-jpa对”Java持久化API”的支持, 包括spring-data-jpa, spring-orm和Hibernate
spring-boot-starter-jdbc对JDBC数据库的支持
spring-boot-starter-jersey对Jersey RESTful Web服务框架的支持
spring-boot-starter-jta-atomikos对JTA分布式事务的支持, 通过Atomikos实现
spring-boot-starter-jta-bitronix对JTA分布式事务的支持, 通过Bitronix实现
spring-boot-starter-mailjavax.mail的支持
spring-boot-starter-securityspring-security的支持
spring-boot-starter-test对常用测试依赖的支持, 包括JUnit, Hamcrest和Mockito, 还有spring-test模块
spring-boot-starter-thymeleaf对Thymeleaf模板引擎的支持, 包括和Spring的集成
spring-boot-starter-velocity对Velocity模板引擎的支持
spring-boot-starter-web对全栈web开发的支持, 包括Tomcat和spring-webmvc
spring-boot-starter-websocket对WebSocket开发的支持

2.0.3文档在: Table 13.1. Spring Boot application starters

spring-boot-starter-parent

关于它的说明在: 13.2 Maven 它有一些默认的设置.

  • 默认为JDK1.8的编译等级(2.0 version)
  • UTF-8编码支持
  • Maven父模块,大概就是..已经从spring-boot-dependencies继承manages , 某些POM的 Dependency 可以忽略版本配置(Maven dependencyManagement继承特性 )..

对于非web应用

  • 不能引用 starter-web 不然就会启动tomcat
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 启动类
@EnableAutoConfiguration //自动配置
@EntityScan("com.yang.spider.model")//告知实体包
@EnableJpaRepositories("com.yang.spider.dao")//告知JpaRepositorie
@SpringBootConfiguration
@ComponentScan
public class AppMain 
{
 
    public static void main( String[] args )  {
    	  SpringApplication.run(AppMain.class, args);
    }
}

主入口类

Spring Boot 项目通常有一个名为 *Application 的入口类(本例是:Example.java),这是一个标准的java入口类

参考: Locating the Main Application Class

@SpringBootApplicationSpring Boot 的核心注解, 它是一个组合注解, 该注解组合了: @Configuration, @EnableAutoConfiguration, @ComponentScan; 若不用 @SpringBootApplication 注解也可以使用这三个注解代替;

  • @EnableAutoConfiguration 让 Spring Boot 根据类路径中的 jar 包依赖为当前项目进行自动配置, 例如, 添加了 spring-boot-starter-web 依赖, 会自动添加 Tomcat 和 Spring MVC 的依赖, 那么 Spring Boot 会对 Tomcat 和 Spring MVC 进行自动配置;

  • Spring Boot 还会自动扫描 @SpringBootApplication 所在类的同级包以及下级包里的 Bean , 所以入口类建议就配置在 grounpID + arctifactID 组合的包名下(springboot下级包config中的WebConfiguration默认会被扫描).

下本项目的目录结构:

├─main
│  └─java
│      └─myproject
│          └─springboot
│              │  Example.java
│              │
│              ├─config
│              │    WebConfiguration.java
│              │
│              ├─controller
│              └─service
├─test
   └─java
        └─myproject
            └─springboot

打包 依赖分离

 <build>
        <plugins>
            <!--设置应用 Main 参数启动依赖查找的地址指向外部 lib 文件夹-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <!-- 项目所依赖的jar位于同一级的lib目录下-->
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--设置 SpringBoot 打包插件不包含任何 Jar 依赖包-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>
                            <groupId>nothing</groupId>
                            <artifactId>nothing</artifactId>
                        </include>
                    </includes>
                </configuration>
            </plugin>
            <!--设置将 lib 拷贝到应用 Jar 外面-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

java -jar xxx.jar 不用指定jar包加载目录; \META-INF\MANIFEST.MF 已经指定了加载

java -cp ./lib -jar xxx.jar

在windows系统注册为开机启动?

https://github.com/winsw/winsw

1. 下载 WinSW

重命名该文件为tny-xjjqr.exe(与服务名一致)

More executables can be added upon request. .NET Framework system requirements
Preinstalled since Windows 10, version 1511 and Windows Server 2016.
Installable since Windows 7 SP1 and Windows Server 2008 R2 SP1.

.NET 7 system requirements
Supported since Windows 10, version 1607, Windows Server (Core) 2012 R2 and Nano Server, version 1809.

2. 创建 XML 配置文件 tny-xjjqr.xml

<service>
  <id>tny-xjjqr</id>
  <name>巡检机主程序 Application</name>
  <description>Spring Boot 3 Application Service</description>
  
  <!-- 可执行命令配置 -->
  <executable>java</executable>
  <arguments>-jar "D:\PROJECT_SERVER\tny-xjjqr-1.0.0-SNAPSHOT.jar" --spring.profiles.active=prod</arguments>
  
  <!-- 日志配置 -->
  <logpath>D:\PROJECT_SERVER\s-logs</logpath>
  <log mode="roll-by-size">
    <sizeThreshold>10240</sizeThreshold> <!-- 10MB 切割 -->
    <keepFiles>4</keepFiles>
  </log>
  
  <!-- 自动重启策略 -->
  <onfailure action="restart" delay="10 sec"/>
  
  <!-- 启动模式 -->
  <startmode>Automatic</startmode>
  <delayedAutoStart>true</delayedAutoStart>
  
  <!-- 环境变量 -->
  <env name="JAVA_HOME" value="C:\Program Files\Java\jdk-23"/>
</service>

3. 安装服务

cd D:\PROJECT_SERVER
 
# 安装服务(自动识别同名的.xml文件)
tny-xjjqr.exe install
 

服务管理命令

操作命令
安装服务.\YourAppService.exe install
卸载服务.\YourAppService.exe uninstall
启动服务.\YourAppService.exe start
停止服务.\YourAppService.exe stop
重启服务.\YourAppService.exe restart
查看状态.\YourAppService.exe status

Spring Boot 的全局配置文件

Spring Boot 的全局配置文件的作用是对一些默认配置的配置值进行修改;

参考: 15. Configuration Classes

  1. Spring Boot 支持基于java注解配置(使用@Configuration 表示这个类是一个spring 配置类)

  2. application.properties 和 application.yml 这两个文件都可以被SpringBoot自动识别并加载, 它的加载位置( classpath/config/ 或者直接类路径classpath/ 或者类子目录的/config/ …)

24.3 Application Property Files
24.6 Using YAML Instead of Propertiess

  1. 自定义配置文件

自定义的xxx.properties配置文件是不会被SpringBoot自动加载的, 需要手动去进行加载, 这里的手动加载一般指的是注解的方式加载: @PropertySource("classpath:xxx.properties")

配置项的使用也很简单, 只要是加载到Spring容器中的配置项都可以直接使用@Value("${key}")的方式来引用, 一般将其配置在字段顶部, 表示将配置项的值赋值给该字段;
https://www.cnblogs.com/V1haoge/p/7183408.html

摘录

  • Spring Boot 使用一个全局的配置文件 application.properties 或 application.yml, 放置在【src/main/resources】目录或者类路径的 /config 下;
  • Spring Boot 不仅支持常规的 properties 配置文件, 还支持 yaml 语言的配置文件; yaml 是以数据为中心的语言, 在配置数据的时候具有面向对象的特征;

常用属性配置

Common Application properties

文档附录: Appendix A. Common application properties

配置文件优先级

配置文件的生效顺序, 会对值进行覆盖:

  1. @TestPropertySource 注解

  2. 命令行参数

  3. Java系统属性(System.getProperties())

  4. 操作系统环境变量

  5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource

  6. 在打包的jar的应用程序配置文件(application.properties, 包含YML和profile变量)

  7. 在打包的jar的应用程序配置文件(application.properties, 包含YML和profile变量)

  8. 在@Configuration类上的@PropertySource注解

  9. 默认属性(使用SpringApplication.setDefaultProperties指定)

这个列表是按优先级排序的(列表中位置高的将覆盖位置低的)

Request 路径问题

//当前项目根路径
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
 
//访问路径
String uri =  request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/stream/";

Spring Boot 的常见注解

@SpringBootConfiguration

package hello;
 
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
 
@SpringBootConfiguration
public class Config {
    @Bean
    public String hello(){
        return "Hello World";
    }
}

@SpringBootConfiguration 继承自 @Configuration, 二者功能也一致, 标注当前类是配置类, 并会将当前类内声明的一个或多个以 @Bean 注解标记的方法的实例纳入到spring容器中, 并且实例名就是方法名; 与 @Configuration所有带@Bean注解的方法都会被动态代理,因此调用该方法返回的都是同一个实例

@ConfigurationProperties(prefix = “spring.datasource”)

配置节点过滤, 注入属性 , 属性类要生成getter和setter函数, 否则映射不成功; 参考: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties, spring的数据源自动配置类

@Conditional (条件加载Bean)

@Configuration

@Configuration Conditional 传入实现org.springframework.context.annotation.Condition 接口的class; 以支持自定义条件判断 @Conditional({MatchCasCondition.class})

注意用法, 示例:

@Configuration
@ConditionalOnProperty(name = "sny.apijson.enabled", havingValue = "true", matchIfMissing = false)

其他条件 @ConditionalOnBean: 当容器里有指定Bean的条件下 @ConditionalOnClass: 当类路径下有指定类的条件下 @ConditionalOnExpression: 基于SpEL表达式作为判断条件; 见下 @ConditionalOnMissingBean: 当容器里没有指定Bean的情况下 @ConditionalOnMissingClass: 当类路径下没有指定类的条件下 @ConditionalOnNotWebApplication: 当前项目不是Web项目的条件下 @ConditionalOnProperty: 指定的属性是否有指定的值 // 例如 @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "true", matchIfMissing = true)

@ConditionalOnSingleCandidate: 当指定Bean在容器中只有一个, 或者虽然有多个指定首选Bean @ConditionalOnWebApplication: 当前项目是Web项目的条件下; @ConditionalOnJava: 基于JV版本作为判断条件 @ConditionalOnJndi: 在JNDI存在的条件下差在指定的位置 @ConditionalOnResource: 类路径是否有指定的值

配置优先级 @Order

注解@Order或者接口Ordered的作用是定义Spring IOC容器中Bean的执行顺序的优先级, 而不是定义Bean的加载顺序, Bean的加载顺序不受@Order或Ordered 接口的影响

order的规则:

  • order 的值越小, 优先级越高
  • order 如果不标注数字, 其默认值是int最大值, 最低优先级
  • 该注解等同于实现Ordered接口getOrder方法, 并返回数字;

默认的MVC Security配置的优先级是 100

@Order(100)
public abstract class WebSecurityConfigurerAdapter implements
		WebSecurityConfigurer<WebSecurity> {
 
        }

根据配置 确定是否启用配置Bean @ConditionalOnProperty

@ConditionalOnProperty

public @interface ConditionalOnProperty {
 
    String[] value() default {}; //数组, 获取对应property名称的值, 与name不可同时使用  
  
    String prefix() default "";//property名称的前缀, 可有可无  
  
    String[] name() default {};//数组, property完整名称或部分名称(可与prefix组合使用, 组成完整的property名称), 与value不可同时使用  
  
    String havingValue() default "";//可与name组合使用, 比较获取到的属性值与havingValue给定的值是否相同, 相同才加载配置  
  
    boolean matchIfMissing() default false;//缺少该property时是否可以加载; 如果为true, 没有该property也会正常加载; 反之报错  
  
    boolean relaxedNames() default true;
} 

实例

@ConditionalOnProperty(name="spring.artemis.embedded.enabled", havingValue="true")

@ConditionalOnProperty(name="spring.artemis.embedded.enabled", havingValue="false", matchIfMissing = true)

Spring Boot 所有自动配置的Class列表

参考文档 Auto-configuration Classes

auto-configuration classes provided by Spring Boot, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with —debug or -Ddebug or, in an Actuator application, use the conditions endpoint).

例如JDBCTemplate 对应的自动配置是JdbcTemplateAutoConfiguration 其源码:

/**
 * {@link EnableAutoConfiguration Auto-configuration} for {@link JdbcTemplate} and
 * {@link NamedParameterJdbcTemplate}.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @author Kazuki Shimizu
 * @since 1.4.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(JdbcProperties.class)
@Import({ JdbcTemplateConfiguration.class, NamedParameterJdbcTemplateConfiguration.class })
public class JdbcTemplateAutoConfiguration {
 
}

Spring Boot 单元测试

  • 引入
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  • 单元测试
//在junit 测试类注解
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppMain.class)//classes = AppMain.class  指定应用的主入口类
public class TestMybits {
    @Autowired
	SqlSessionTemplate sqlSessionTemplate;
    //然后这里的单元测试就拥有了 springboot 环境了
	@Test
	public void test() {}
		PostMapper mapp = sqlSessionTemplate.getMapper(PostMapper.class);
		Post post = new Post();
		post.setContent("123321");
		post.setMark("BATCH");
		//mapp.insert(post);
		System.out.println("insert="+post);
	}
}

Spring Boot TLS (https)

  1. 生成证书

    • 导出证书(cer)
      keytool -exportcert -alias tomcat_k -file ./tomcat_k.cer -storepass abcd369258147.com -keystore ./rsa_key.keystore

    • 查看证书信息(cer)
      keytool -list -v -alias tomcat_k -keystore "F:\test\rsa_key.keystore" -storepass abcd369258147.com
      keytool -list -v -keystore "F:\test\rsa_key.keystore" -storepass abcd369258147.com

  2. 复制证书到classpath目录

  3. 修改 application.properties配置

#端口号
server.port=8443
#证书路径
server.ssl.key-store= classpath:rsa_key.keystore
#密码
server.ssl.key-store-password=tomcat
#证书类型
server.ssl.keyStoreType=JKS
#别名
server.ssl.keyAlias:tomcat_k

Spring MVC 数组参数的问题

前端URL 拼接 http://127.0.0.1:8002/api/book/queryReferenceList?refField=bookType&selects=id&selects=name

后台接受

@GetMapping(value = "/queryReferenceList")
@PreAuthorize("@authService.hasPermission(authentication)")
public ResponseStatus queryReferenceList(@RequestParam String refField, @RequestParam  String[]  selects){
    return new ResponseStatus(ResponseCode.SUCCESS, serviceBean.queryReferenceList(refField, selects));
}

Spring Boot 3.0

Spring Boot 3.0 将在 2022-11-24 初始发布;

2022年1月21日 发布3.0-M1

Remove support for ActiveMQ #28591 Switch to new coordinates for Git Commit ID Maven Plugin #29515 Remove support for Hazelcast 3 #29287 Update Hibernate dependency management to use -jakarta artifacts #28867 Drop support for Jersey until a Spring Framework 6-compatible jersey-spring module is available #28808 Drop support for embedding EhCache 3 until it supports Jakarta EE 9 #28800 Drop support for embedding Infinispan until it supports Jakarta EE 9 #28799 Drop support for CommonsMultipartResolver as it has been removed in Spring Framework 6 #28782 Drop support for REST Assured until it supports Jakarta EE 9 #28722 Drop support for Jolokia until it supports Servlet 5 #28704 Drop support for auto-configuring Hibernate metrics until a Jakarta EE 9 variant of hibernate-micrometer is available #28703 Remove support for pooled-jms as it is not JMS 3.0 compatible #28701 Remove dependency management for Apache Johnzon #28616 Provide dependency management for Eclipse Yasson #28614

Remove support for ActiveMQ #28591 Remove support for H2 Console #28590 Remove support for Atomikos #28589 Remove support for Ehcache 2.x #28588 Remove support for Java’s deprecated SecurityManager #28213

Raise the minimum supported version of Java to 17 #28101 Raise the minimum supported version of Gradle to 7.3 #28100

Spring-Boot-3.0-Release-Notes 正式发布2022-11-28

踩坑指南

跨域问题

MVC的全局跨越配置 WebMvcConfigurer

@Configuration
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    	 registry.addMapping("/**")//地址
	         .allowedOrigins("*")//允许地址
	         .allowedMethods("*")//允许方法
	         .allowedHeaders("*")//允许头
	         .allowCredentials(true)//允许cookie
             .maxAge(3600);//多长时间 不检查
    }
    ...
}

servletResponse.setHeader(“Access-Control-Allow-Origin”, ""); servletResponse.setHeader(“Access-Control-Allow-Headers”, ""); servletResponse.setHeader(“Access-Control-Allow-Credentials”, “true”);

Spring 中对 CORS 规则的校验, 都是通过委托给 org.springframework.web.cors.DefaultCorsProcessor 实现的; 它先读取Vary的(Response)响应头, 根据这个内容决定是否设置跨域响应头

boolean org.springframework.web.cors.DefaultCorsProcessor.processRequest(@Nullable CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) throws IOException

	public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
 
		Collection<String> varyHeaders = response.getHeaders(HttpHeaders.VARY);
		if (!varyHeaders.contains(HttpHeaders.ORIGIN)) {
			response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
		}
		if (!varyHeaders.contains(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD)) {
			response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
		}
		if (!varyHeaders.contains(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)) {
			response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
		}
 

记一数据库连接池/ redis 十分钟左右断开

MySQL

  1. 与MySQL 相关连接超时配置无关.
  2. 与连接池无关..

在mysql 日志

  • IP address ‘xxx’ could not be resolved: 不知道这样的主机;

原因Server在本地内存中维护了一个非本地的Client TCP cache, 这个cache中包含了远程Client的登录信息, 比如IP地址, hostname等信息; 如果Client连接到服务器后, Mysql首先会在本地TCP池中根据IP地址解析客户端的hostname或者反解析, 如果解析不到, 就会去DNS中进行解析, 如果还是解析失败就在error log中写入这样的警告信息; ”;

配置文件后在My.ini 文件 [mysqld] 下面增加可解决

sip-host-cache
skip-name-resolve

然而与此无关..

最最终抓包调试, 九成九路由器问题! 没救了, 调毛..

源码调试

N_SpringBoot_源码调试一则

附录 application.properties 属性配置

文档附录: Appendix A. Common application properties

Common Application Properties springboot附录_属性配置



扩展阅读

官页 - 基本所有Spring project的文档

大佬的博客 - wangb_java 大佬的博客 - A哥(YourBatman)