1. Create a SpringBoot project
concept
Spring Boot is a new framework provided by the Pivotal team, designed to simplify the initial setup and development of new Spring applications. The framework uses a specific way to configure, so that developers no longer need to define boilerplate configuration. In this way, Spring Boot aims to be a leader in the burgeoning field of rapid application development.
Spring Boot Features
- Create a standalone Spring application
- Embedded Tomcat without deploying WAR files
- Simplified Maven configuration
- Automatically configure Spring
- Provides production-ready features such as metrics, health checks and external configuration
- Absolutely no code generation and no configuration required for XML
Build the Spring Boot project
(1) Create a project, select Spring starter Project (you need to install Spring Tool Suite in Eclipse first), and press Next:
(2) Fill in various information related to the project, and then Next:
(3) Select the required Dependency, then Next:
(4) Finally, "Finish" starts to download the jar package, which takes a long time.
run the project
Project structure introduction
As shown in the figure above, the Spring Boot infrastructure consists of three files:
- src/main/java program development and main program entry
- src/main/resources configuration file
- src/test/java test program
Also, the directory suggested by spingboot results in the following:
root package structure: com.example.myproject
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- controller
| +- CustomerController.java
|
1. Application.java is recommended to be placed under the root directory, which is mainly used for some framework configurations
. 2. The domain directory is mainly used for the entity and data access layer (Repository)
3. The service layer is mainly business code
4. The controller is responsible for page access control
pom.xml
There are two modules by default in the pom.xml file:
spring-boot-starter : core module, including auto-configuration support, logging and YAML;
spring-boot-starter-test : Test modules, including JUnit, Hamcrest, Mockito.
start a single controller
1. Create a controller
package com.ailianshuo.helloword.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String hello() {
return "Hello World";
}
}
@RestController means that the methods in the controller are output in json format, no need to write any jackjson configuration
2. Start the controller to prepare
to start a single controller according to the above code. You need to add the following code:
(1) @EnableAutoConfiguration: The function is to let Spring Boot automatically configure the Spring framework according to the dependencies declared by the application, which reduces the the workload of developers. (You can also use @SpringBootApplication which is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with default properties)
(2) Start the program:
public static void main(String[] args) throws Exception {
SpringApplication.run(**.class, args);
} The
complete code is as follows:
@EnableAutoConfiguration
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String hello() {
return "Hello World";
}
public static void main(String[] args) {
SpringApplication.run(HelloWorldController.class);
}
}
3. Start a single controller
(1) Right-click the main method in HelloWorldController, Run As -> Spring Boot App, and the project can be started.
(2) The compiler displays the following content, that is, the startup is successful.
2017-08-19 11:12:49.814 INFO 4164 — [main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-19 11:12:49.819 INFO 4164 — [main] cahcontroller.HelloWorldController : Started HelloWorldController in 3.351 seconds (JVM running for 4.573)
(3) Visit http://localhost:8080/hello in the browser to see the effect.
Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot
Second, the rapid construction of RESTfull API simple projects
Edit pom.xml
[html] view plain copy
- <?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.lyw</groupId>
- <artifactId>springboot02</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>springboot02</name>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.4.0.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>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
Briefly explain the above configuration
First look at the dependencies of the Spring-boot-start-web package
It can be seen that this package is actually some log packages and the built-in Tomcat JSON package SpringMVC/Web package, which almost explains why it runs directly.
In fact, this can be understood as simply encapsulating Spring to make our configuration more convenient.
The introduction of spring-boot-devtools and the learning of its dependent packages
This package contains some of Spring's core packages. . .
spring-boot-maven-plugin finally added a SpringBoot Maven plugin
Start writing code. . .
Springboot2Application.java
[java] view plain copy
- package com.lyw;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- public class Springboot02Application {
- public static void main(String[] args) {
- SpringApplication.run(Springboot02Application.class, args);
- }
- }
User.java
[java] view plain copy
- package com.lyw.bean;
- import java.util.Date;
- /**
- * Title: User Description: Entity class Company: blog.csdn.net/lu1005287365/
- *
- * @author L lulu
- */
- public class User {
- private Integer id;
- private String name;
- private Date date;
- private char sex;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Date getDate() {
- return date;
- }
- public void setDate(Date date) {
- this.date = date;
- }
- public char getSex() {
- return sex;
- }
- public void setSex(char sex) {
- this.sex = sex;
- }
- }
UserControoler.java
[java] view plain copy
- package com.lyw.controller;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import com.lyw.bean.User;
- @RestController
- @RequestMapping(value = "/user")
- public class UserController {
- @RequestMapping
- public String index() {
- return "Hello BeiJing";
- }
- @RequestMapping(value = "/getMap")
- public Map<String, Object> getThisMap(String msg) {
- Map<String, Object> map = new HashMap<>();
- map.put("Name", "LYW");
- map.put("Sex", "Big Guys");
- map.put("Message", msg);
- return map;
- }
- @RequestMapping(value = "/getUser/{name}/{sex}")
- public User getUser (athPathVariable String name, athPathVariable char sex)
- User user = new User();
- user.setId(12);
- user.setName(name);
- user.setDate(new Date());
- user.setSex(sex);
- return user;
- }
- }
Run the project:
Run the main method directly or use the maven command: spring-boot:run
The above is the result of the operation. .
explain
@RestController annotation: Looking at the source code, it actually encapsulates another layer to combine the two annotations @Controller and @RsponseBody
In this way, you should also have a preliminary understanding of SpringBoot. . . and will be easy to use
3. Spring Boot implements multi-environment configuration
In actual projects, we generally place some configuration files, which distinguish the environment. The general environment includes dev, test, prep, and prod, which correspond to development, testing, pre-release, and production. So how to implement different environments and use different configuration files in the spring boot project.
Step 1: Define application.properties for different environments
application.properties stores some common configuration.
And the most important configuration [email protected]@
application-dev.properties corresponds to the development environment
application-test.properties corresponds to the test environment
application-prep.properties corresponds to the pre-production environment
application-prod.properties corresponds to the production environment
Step 2: Define profile in pom
Step 3: maven command package
package -Dmaven.test.skip=true -Pdev
Then the configuration of application-dev.properties and application.properties will be entered into the package at this time.
Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot
Fourth, Spring Boot application monitoring
Getting Started: Actuator Plugin
The Actuator plugin is a service provided natively by SpringBoot, which can be used to output many endpoint information in the application by exposing endpoint routing . Let's fight it!
- Add dependencies to pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
After starting the Spring Boot application, you can get some state information of the application by simply entering the endpoint information in the browser.
Common endpoints are listed as follows, you can try them one by one in detail:
Of course, only the /health
and /info
endpoints can be used at this time, and the others cannot be accessed due to permission issues. If you want to access the specified endpoint, you can add relevant configuration items in the yml configuration. For example, /metrics
the endpoint needs to be configured:
endpoints:
metrics:
sensitive: false
At this point the browser accesses the /metrics endpoint to get information such as the following:
Of course, you can also open all endpoint permissions, just configure the following:
endpoints:
sensitive: false
After all, the monitoring capabilities provided by the Actuator plug-in are limited, and the UI is relatively simple, so a more mature tool is needed.
Spring Boot Admin Monitoring System
SBA is a further evolution based on Actuator, which is a monitoring tool for UI beautification and encapsulation of Actuator interfaces. Let's experiment.
- First, create a Spring Boot Admin Server project as a server
Add the following dependencies to pom.xml:
Then enable Spring Boot Admin by annotating the main class of the application
Start the program, and the browser opens to localhost:8081
view the Spring Boot Admin main page:
At this time, the Application column is empty, waiting for the application to be monitored to join
- Create a Spring Boot application to monitor
Add the following dependencies to pom.xml
Then add the following configuration to the yml configuration to register the application to the Admin server:
As soon as the Client application starts, the Admin service immediately pushes a message, telling you that AdminTest is online:
At this point, go to the Admin main interface and find that the Client application has indeed been registered:
- View Details
- View Metrics
- View Environment
- View JMX
- View Threads
- View Trace and Details
Click JOURNAL at the top, and you will see the event changes of the monitored application:
It can be clearly seen from the figure that the application jumps from the state of REGISTRATION → UNKNOWN → UP .
This will try all the endpoint information provided by the Actuator plugin in SBA.
Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot
Five, Spring Boot log management
By default, Spring Boot's logs are output to the console and do not write to any log files.
To let Spring Boot output log files, the easiest way is to configure the logging.path key value in the application.properties configuration file, as follows: (The log file is spring.log)
logging.path=/var/log
The second method is to configure the logging.file key value in the application.properties configuration file, as follows:
logging.file=/var/log/myapp.log
The two configuration methods are suitable for the development stage, but there are certain problems in the deployment. For example, when deploying to different environments, it may be necessary to modify the application.properties file, which means that it needs to be repackaged and deployed again, which is inconvenient.
In view of this, Spring Boot provides a way to override the key values in the application.properties configuration file, by specifying parameters on the command line to achieve overriding - at runtime, the command line parameters are treated as standard system properties, as follows :
java -jar -Dlogging.path=/tmp myapp.jar
Later, you can also override this value when invoking Spring Boot's Maven plugin from the command line. However, using system properties directly is invalid for the plugin approach. You need to use the run.jvmArguments parameter to specify the system property and set the desired value:
mvn spring-boot:run -Drun.jvmArguments="-Dlogging.path=/tmp"