Introduction
Before also did not study the spring framework, recently springboot popular to fill this area of knowledge, so according to Springboot official online English course began HelloWorld, step on a few pits, record the learning process. What are the advantages of Springboot
Springboot can help us quickly build applications and automatically assemble missing beans, allowing us to focus more on business development than on infrastructure. It has a few advantages: it has built-in Tomcat and jetty containers, avoids the need to configure containers, deploy war packages, and so on, to automatically add missing beans simplifies XML configuration and does not even require XML to configure Beans for getting started jdk1.8+ (JDK1.7 can, but the official example thread used some lambda expressions, lambda expressions are only supported in versions JDK1.8 and above) MAVEN 3.0+ Ide:idea (development tools I chose idea) build HelloWorld Web App creates an empty Maven project
Use idea to create a MAVEN project, where GroupID and Artifactid can be arbitrarily specified
We begin to configure the Pom file, specifying that the HelloWorld parent project is spring-boot-starter-parent, so that we do not need to specify some dependent versions of Springboot (as specified in the parent project).
The Pom.xml files are configured as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "htt P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apach E.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>org.springframework
</groupId> <artifactId>helloworld</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-start er-parent</artifactid> <version>1.5.2.RELEASE</version> </parent> <dependencie s> <dependency> <groupId>org.springframework.boot</groupId> <artif actid>spring-boot-starter-web</artifactid> </dependency> </dependencies> <propert Ies> <JAVA.Version>1.8</java.version> </properties> <build> <plugins> <plug In> <groupId>org.springframework.boot</groupId> <artifactid>spring-bo ot-maven-plugin</artifactid> </plugin> </plugins> </build> </project> ;
The Spring-boot-maven-plugin plugin helps us to generate a jar file that can be run directly when we use the MVN Package command. (Spring-boot-maven-plugin effect) Create a web App
Create a controller, directory in Src/main/java/hello/hellocontroller.java
Package Hello;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RestController;
/**
* @author zengrong.gzr
* @Date 2017/03/11 * *
@RestController public
class Hellocontroller {
@RequestMapping ("/") public
String Index () {
return ' Greetings from Spring boot! ';
}
@RequestMapping ("/helloworld") public
String Hello () {
return "Hello world!";
}
}
Create a Web application, directory in Src/main/java/hello/hellocontroller.java
Package Hello;
Import Org.springframework.boot.CommandLineRunner;
Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.annotation.Bean; /** * @author ZENGRONG.GZR * @Date 2017/03/11 * * @SpringBootApplication public class Application {public static VO
ID Main (string[] args) {Springapplication.run (application.class, args);
}//Specify the name of the next Bean @Bean (name = "GZR") public Commandlinerunner Commandlinerunner (ApplicationContext ctx) {
return new Commandlinerunner () {@Override public void run (String ... args) throws Exception {
SYSTEM.OUT.PRINTLN ("Let's inspect the beans provided by Spring Boot:");
string[] Beannames = Ctx.getbeandefinitionnames (); for (String beanname:beannames) {System.out.println (beanname);
}
}
}; }
}
As you can see, we don't need the XML to configure the bean, and we don't need to configure the Web. Net file, which is a pure Java application, and we don't need to deal with complex configuration relationships. Run the app
You can run the app directly from the command line
$ MVN Package && Java-jar Target/helloworld-1.0-snapshot.jar
Of course I prefer to use idea to run, so you can debug see Springboot initialization process, the configuration process is as follows
Let's debug with idea to see if "Error:java:Compilation failed:internal Java Compiler Error" errors occur at compile time (as shown below), we need to modify the idea's default compiler settings
Modify the compiler settings as follows
We can see the results of the operation in the console, intercept a section of the image below, you can see the printed beans, including Hellocontroller, and we specify the name of the GZR, etc.
Let's examine the Web service, run at the command line
$ Curl localhost:8080
Greetings from Spring boot!
$ Curl Localhost:8080/helloworld
Hello world!%
Service Uptime ~ Adding test Cases
We first add the required dependencies in the POM to the test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>
Add a simple test case, directory in Src/test/java/hello/hellocontrollertest.java
Package Hello;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import ORG.SPRINGFRAMEWORK.BOOT.TEST.AUTOCONFIGURE.WEB.SERVLET.AUTOCONFIGUREMOCKMVC;
Import Org.springframework.boot.test.context.SpringBootTest;
Import Org.springframework.http.MediaType;
Import Org.springframework.test.context.junit4.SpringRunner;
Import ORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;
Import Org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
Import static org.hamcrest.Matchers.equalTo;
Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author ZENGRONG.GZR * @Date 2017/03/11 * * @RunWith (Springrunner.class) @SpringBootTest @AutoConfigureMockMvc Pub
Lic class Hellocontrollertest {@Autowired private MOCKMVC mvc; @Test public void Gethello () throws Exception {MVC. Perform (Mockmvcrequestbuilders.get ("/"). Accept (Mediatype.application_json)). Andexpect (Status (). IsOk ())
. Andexpect (Content (). String (Equalto ("Greetings from Spring boot!")); }
}
It is easy to run the test directly
Now that we have simulated HTTP requests for testing, we can also write a simple full-stack integration test via Springboot:
Src/test/java/hello/hellocontrollerit.java
Package Hello;
Import Org.junit.Before;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.boot.context.embedded.LocalServerPort;
Import Org.springframework.boot.test.context.SpringBootTest;
Import Org.springframework.boot.test.web.client.TestRestTemplate;
Import org.springframework.http.ResponseEntity;
Import Org.springframework.test.context.junit4.SpringRunner;
Import Java.net.URL;
Import static org.hamcrest.Matchers.equalTo;
Import static org.junit.Assert.assertThat; /** * @author ZENGRONG.GZR * @Date 2017/03/11 */@RunWith (Springrunner.class) @SpringBootTest (webenvironment = Springbo
OtTest.WebEnvironment.RANDOM_PORT) public class Hellocontrollerit {@LocalServerPort private int PORT;
Private URL base;
@Autowired private testresttemplate template; @Before public void SetUp () throws Exception {this.base = new URL ("http://localhost:" + Port + "/"); } @Test public void Gethello () throws Exception {responseentity<string> response = Template.getfor
Entity (Base.tostring (), string.class);
Assertthat (Response.getbody (), Equalto ("Greetings from Spring boot!"); }
}
With webenvironment = SpringBootTest.WebEnvironment.RANDOM_PORT We can have the built-in server start on a random port. Add a production management Service
Usually when we are building a website, we may need to add some management services. Springboot provides several out-of-the-box management services, such as health checks, dump data, and more.
We first add the dependency required for the management service in the POM
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> Spring-boot-starter-actuator</artifactid>
</dependency>
Run the program directly, you can see the console output the management services provided by many Springboot
We can easily check the health status of the app
$ curl Localhost:8080/health
{"Status": "Up"}
$ curl localhost:8080/dump
{"timestamp": 1489226509796, " Status ": 401," error ":" Unauthorized "," message ":" Full authentication was required to access this resource. "," path ":"/dump "}
When we perform curl Localhost:8080/dump we can see that the return status is "unauthorized", and that the dump, bean and other permissions need to be closed for security control to be accessible. So how to shut down. This can be done by annotations, or by configuring Application.properties.
Here we choose the second one, create a new application.properties file under the Src/main/resources folder (the framework will automatically scan the file) and add the configuration to the file as configured management.security.enabled= False.
Once the app is launched, we'll run the Curl Localhost:8080/beans command to see the command line print out all the beans loaded by the system. Source Download
Attach source code