A lot of netizens will ask me from time to time, how to test the Spring boot project, how to deploy it, what are the good deployment scenarios in production? This article will introduce how spring boot is developed, debugged, packaged, and put into production on the last launch.
Development Phase Unit Testing
The most important part of the development phase is unit testing, and Springboot support for unit testing is well established.
1. Add the Spring-boot-starter-test package reference in the POM package
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
2. Development Test Class
In the simplest case of HelloWorld, the class header of the test class needs to be added: @RunWith (springrunner.class)
and @SpringBootTest
annotations, add at the top of the test method, Finally, you can run it by right-clicking on the method.
@RunWith(SpringRunner.class)@SpringBootTestpublic class ApplicationTests {@Testpublic void hello() {System.out.println("hello world");}}
In practice, you can inject DAO layer code or service layer code to test validation according to the normal use of the project, Spring-boot-starter-test provides a lot of basic usage, and, more importantly, adds support for controller layer testing.
//simple validation result set is correct assert. (3usermapper.< Span class= "NA" >getall (). //validating result set, prompting assert. (" error, the correct return value is ", status == 200); assert. (" error, the correct return value is ", status != 200
The introduction of the MockMvc
support for the controller layer test, a simple example is as follows:
PublicClassHellocontrolertests{PrivateMockmvcMvc;Initialize execution@BeforePublicvoidSetUp()ThrowsException{Mvc=Mockmvcbuilders.Standalonesetup(NewHellocontroller()).Build();}Verify that the controller responds properly and prints the returned results@TestPublicvoidGethello()ThrowsException{Mvc.Perform(Mockmvcrequestbuilders.Get("/hello").Accept(MediaType.Application_json)).Andexpect(Mockmvcresultmatchers.Status().IsOk()).Anddo(Mockmvcresulthandlers.Print()).Andreturn();}Verify that the controller is responding properly and that the returned results are correct@TestPublicvoidTesthello()ThrowsException{Mvcperform (mockmvcrequestbuilders. Get ( "/hello" (mediatype. Application_json. (status (). ()) . (content (). (equalto ( "Hello World" } /span>
Unit testing is the first barrier to verify your code, to develop every part of the code to do unit testing habits, do not wait until all integration before testing, integration because more attention to the overall performance, it is easy to omit the code underlying bugs.
Integration Testing
After the overall development of the integration test, the Spring Boot Project launch Portal in the application class, directly run the running method can start the project, but in the course of debugging we must constantly debug the code, If you need to manually restart the service every time you modify the code, Spring boot is very thoughtful about the support of the hot deployment and is easy to debug in a Web project.
The POM needs to add the following configuration:
<dependencies><dependency><groupid>org.springframework.boot</groupId> <artifactid>spring-boot-devtools</artifactId> <optional>true< c4></optional> </dependency></dependencies><build> <plugins> <plugin> <groupid>org.springframework.boot</groupId> <artifactId> Spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork > </configuration> </plugin></plugins></build>
After adding the above configuration, the project supports a hot deployment and is very convenient for integration testing.
Production line
In fact, I think this stage, it should be relatively simple is generally divided into two kinds, one is packaged into a jar package to execute directly, and the other is packaged into a war package placed under the Tomcat server.
Make a jar package
If you are using MAVEN to manage your project, execute the following command to
cd 项目跟目录(和pom.xml同级)mvn clean package## 或者执行下面的命令## 排除测试代码后进行打包mvn clean package -Dmaven.test.skip=true
After the package is complete, the jar package is generated to the target directory, and the name is typically the project name + version number. jar
Start the jar Package command
-jar target/spring-boot-scheduler-1.0.0.jar
In this way, the service cannot be accessed as long as the console shuts down. Below we use the way to run in the background to start:
-jar target/spring-boot-scheduler-1.0.0.jar &
You can also choose to read different configuration files at startup
-jar app.jar --spring.profiles.active=dev
You can also set JVM parameters at boot time
-Xms10m -Xmx80m -jar app.jar &
Gradle
If you are using Gradle, use the following command to package
-jar build/libs/mymodule-0.0.1-SNAPSHOT.jar
Fight a war bag
The war package can generally be implemented in two ways, the first one can be exported through the development tool of Eclipse, the war package, the other is to use the command to complete, here the main introduction of the latter
1. Maven project, modify POM Package
Will
<packaging>jar</packaging>
Switch
<packaging>war</packaging>
2. When packing, exclude Tomcat.
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency>
Set the scope property here to provided so that the jar package will not be included in the resulting war, because servers such as Tomcat or jetty will provide the relevant API classes at runtime.
3. Registration Startup Class
Create Servletinitializer.java, inherit Springbootservletinitializer, overwrite configure (), register the startup class application. When the external Web application server builds the Web application context, the startup class is added.
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); }}
Final execution
mvn clean package -Dmaven.test.skip=true
will be generated under target directory: Project name + version number. war file, copy to Tomcat server to start.
Gradle
If you are using Gradle, the basic step-up is the same, Build.gradle added support for the war, excluding Spring-boot-starter-tomcat:
‘war‘...dependencies { compile("org.springframework.boot:spring-boot-starter-web:1.4.2.RELEASE"){ exclude mymodule:"spring-boot-starter-tomcat" }}...
Use the build command again
gradle build
The war is generated under the Build\libs directory.
Production operations view values for JVM parameters
You can customize the Jinfo command with Java:
-flags pid
To see what GC, Cenozoic, and older generations of memory were used after the jar was started, as an example:
-XX:CICompilerCount=3 -XX:InitialHeapSize=234881024 -XX:MaxHeapSize=3743416320 -XX:MaxNewSize=1247805440 -XX:MinHeapDeltaBytes=524288 -XX:NewSize=78118912 -XX:OldSize=156762112 -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseParallelGC
-XX:CICompilerCount
: Maximum number of parallel compilations
-XX:InitialHeapSize
and -XX:MaxHeapSize
: Specify the initial and maximum heap memory sizes for the JVM
-XX:MaxNewSize
: Maximum assignable size of cenozoic memory in the JVM heap area
- ...
-XX:+UseParallelGC
: Garbage collection using parallel collector
How to restart
Simple Rough
Kill the process directly and start the jar package again
-ef|grep java ##拿到对于Java程序的pidkill -9 pid## 再次重启Java -jar xxxx.jar
Of course this approach is more traditional and violent, so it is recommended that you use the following method to manage
Script execution
If you are using MAVEN, you need to include the following configuration
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration></plugin>
If you are using Gradle, you need to include the following configuration
{ executable = true}
Starting mode:
1, can be directly ./yourapp.jar
to start
2, registered as a service
You can also make a soft link to your jar package and add it to the init.d
, then start with a command.
INIT.D Example:
-s /var/yourapp/yourapp.jar /etc/init.d/yourappchmod +x /etc/init.d/yourapp
This allows you to use stop
or restart
command to manage your app.
/etc/init.d/yourapp start|stop|restart
Or
service yourapp start|stop|restart
To this springboot project how to test, joint and packaged production has been introduced, you can find time to study the Springboot automation, and the combination of spring boot and Docker use.
Sample Code-github
Sample code-Cloud Code
Reference: Installing Spring Boot Applications
Springboot (12): Springboot How to test a packaged deployment