-
Introduction to spring boot
-
maven dependency
<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.ljb</groupId>
<artifactId>spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outoutEncoding>UTF-8</project.reporting.outoutEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<!-- using spring boot without parent pom -->
<!--
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.12.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<!-- package as an executable jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- for upgrade -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- Start class
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
- Sample code
@RestController
public class HelloController {
@RequestMapping("/helloworld")
public String index() {
return "Hello World!";
}
}
- application.yaml configuration file
server:
port: ${
random.int[10000,19999]} #使用随机数
- Test code
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
//省略一部分import
@RunWith(SpringJUnit4ClassRunner.class)//引入Spring对JUnit4的支持
@SpringApplicationConfiguration(classes = HelloApplication.class)//指定SpringBoot的启动类
@WebAppConfiguration //开启Web应用的配置,用于模拟ServletContext。
public class TestHelloController {
private MockMvc mvc;//用于模拟调用Controller的接口发起请求
@Test
public void hello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/helloworld").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World test auto restartddfddf!")));
}
}
- Some of the interface actuators provided by the
actuator are a standardized implementation framework for the collection of environment variables, garbage collection information, memory information, thread pool information, etc., just add maven dependency and use it out of the box.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- Use of @Value
Note: @Value is a function provided by spring itself
- add to the application.yaml file
book:
name: spring cloud
author: ljb
- Add the corresponding entity class
@Component
public class BookEntity {
@Value("${book.name}")
private String name;
@Value("${book.author}")
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
- Control layer for dependency injection
@RestController
public class HelloController {
@Autowired
private BookEntity bookEntity;
@RequestMapping("/book")
public BookEntity bookMsg() {
return bookEntity;
}
}
In spring boot, the file name of the multi-environment configuration needs to meet the format of application-{profile}.yaml, where {profile} corresponds to your environment identifier and includes the following three types:
- application-dev.yaml development environment
- application-test.yaml test environment
- application-prod.yaml production environment
If spring.profiles.active=test is configured in application.yaml, the configuration file of application-test.yaml will be loaded
-
Automatic restart
After the development tool is activated, any modification to any file in the Classpath will cause the application to restart. In order to make the restart fast enough, classes that will not be modified (such as classes in third-party JAR files) are loaded into the base class loader, and the application code is loaded into a separate restart class loader. When a change is detected, only the restart class loader is restarted. Some resources in the Classpath do not need to be restarted after the resource is changed. Try templates like Thymeleaf can be edited directly without restarting the application. The static resources in static or public do not need to restart the application, so spring boot develops tools to exclude the following directories when restarting: /META-INFO/resources, /resources, /resources, /static, /public, and /templates .
You can set the spring-devtools.restart.exclude property to override the default restart exclude directory. -
Turn on automatic restart
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
-
Command mode
encapsulates the request from the client into an object, so that you can use different requests to parameterize the client. It can be used to realize the decoupling of "behavior requester" and "behavior realization" so that the two can adapt to changes. -
Eureka
uses eureka for service registration discovery@EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(EurekaServerApplication.class).web(true).run(args); } }
-
Eureka configuration file
server: port: 1111 eureka: instance: hostname: localhost client: register-with-eureka: false #不向注册中心注册自己 fetch-registry: false #不去拉去服务 serviceUrl: defaultZone: http://${ eureka.instance.hostname}:${ server.port}/eureka/
-
Use ribbon load call
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency>
-
clinet side call code
@SpringBootApplication @EnableAutoConfiguration @EnableDiscoveryClient public class ClientApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } }
@RestController public class ClinetController { @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET) public int printInstanceId() { return restTemplate.getForEntity("http://SERVER/server", Integer.class).getBody(); } }
- client configuration file
spring: application: name: CLIENT server: port: 8085 eureka: client: serviceUrl: defaultZone: http://localhost:1111/eureka/
-
Server code
@SpringBootApplication @EnableAutoConfiguration @EnableDiscoveryClient public class ServertApplication { public static void main(String[] args) { SpringApplication.run(ServertApplication.class, args); } }
@RestController public class ServerController { @Autowired private DiscoveryClient client; @RequestMapping(value = "/server", method = RequestMethod.GET) public int printInstanceId() { ServiceInstance service = client.getLocalServiceInstance(); return service.getPort(); } }
- Server configuration file
spring: application: name: SERVER server: port: 8092 eureka: client: serviceUrl: defaultZone: http://localhost:1111/eureka/ healthcheck: enabled: true