SpringBoot overview
SpringBoot provides a way to use Spring quickly. Based on the idea that convention is better than configuration, developers do not have to switch thinking between configuration and logical business, and devote themselves to the coding of logical business, which greatly improves the efficiency of development
SpringBoot features
1) Auto configuration
The automatic configuration of Spring Boot is a run-time (more accurately, application startup) process. Many factors are considered to determine which Spring configuration should be used and which should not be used. This process is done automatically by SpringBoot.
2) Start dependence
Start dependency is essentially a Maven Project Object Model (POM), which defines the transfer dependency on other libraries. These things together support a certain function.
In short, start dependency is to package the coordinates with certain functions and provide some default functions.
3) Auxiliary function
It provides some common non functional features in large projects, such as embedded server, security, indicators, health detection, external configuration, etc.
Note: Spring Boot is not an enhancement to Spring, but provides a way to use Spring quickly.
SpringBoot quick start
Requirements: build the SpringBoot project, define the HelloController.hello() method, and return "Hello SpringBoot!".
Implementation steps:
① Create Maven project
② Import SpringBoot dependency
<!--springboot Project needs inherited parent project--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> <dependencies> <!--web Start dependence of development--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
③ Define Controller
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return " hello Spring Boot !"; } }
④ Write boot class
/** * Boot class. Entry to the SpringBoot project */ @SpringBootApplication public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class,args); } }
⑤ Start test
Quickly build SpringBoot project
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ICOkYPrz-1631353027800)(/images/springboot01.png)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-98eU7rLn-1631353027801)(/images/springboot02.png)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-NqDziCLe-1631353027802)(/images/springboot03.png)]
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qsC4CewP-1631353027804)(/images/springboot04.png)]
Analysis of start dependence principle
- The version information of various technologies is defined in spring boot starter parent, and a set of optimal matching technology versions are combined.
- In various starter s, the coordinate set required to complete this function is defined, and most of the version information comes from the parent project.
- Our project inherits the parent. After introducing the starter, we can easily obtain the required jar package through dependency transfer, and there will be no version conflict and other problems.
Configuration - profile classification
SpringBoot is based on conventions, so many configurations have default values, but if you want to replace the default configuration with your own configuration, you can use application.properties or application.yml (application.yaml) for configuration.
- Default profile name: application
- Under the same level directory, the priority is: Properties > YML > yaml
For example, configure the port with built-in Tomcat
properties:
server.port=8080
yml:
server: port: 8080
Configure -yaml basic syntax
- Case sensitive
- The data value must be preceded by a space as a separator
- Use indentation to represent hierarchical relationships
- The Tab key is not allowed to be used during indentation, and only spaces are allowed (the number of spaces corresponding to tabs of each system may be different, resulting in hierarchy confusion).
- The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
- '#' indicates a comment, which will be ignored by the parser from this character to the end of the line.
server: port: 8080 address: 127.0.0.1 name: abc
Configure -yaml data format
Object (map): a collection of key value pairs.
person: name: zhangsan # Inline writing person: {name: zhangsan}
Array: a set of values arranged in order
address: - beijing - shanghai # Inline writing address: [beijing,shanghai]
Scalar: a single, non separable value
msg1: 'hello \n world' # Single index ignore escape character msg2: "hello \n world" # Double citation recognition escape character
Parameter reference
name: lisi person: name: ${name} # Reference the name value defined above
Configuration - get data - 1
@Value
#Get normal configuration @Value("${name}") private String name; #Get object properties @Value("${person.name}") private String name2; #Get array @Value("${address[0]}") private String address1; #Get scalar @Value("${msg1}") private String msg1;
Evironment
@Autowired private Environment env; System.out.println(env.getProperty("person.name")); System.out.println(env.getProperty("address[0]"));
Configuration - get data - 2
@ConfigurationProperties
Note: prefix must be written
@Component @ConfigurationProperties(prefix = "person") public class Person { private String name; private int age; private String[] address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String[] getAddress() { return address; } public void setAddress(String[] address) { this.address = address; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Configuration - profile
-
profile is used to configure the dynamic switching function in different environments.
-
profile configuration mode
-
Multiple profile file mode: multiple profiles are provided, each representing an environment.
Application dev.properties/yml development environment
application-test.properties/yml test environment
application-pro.properties/yml production environment -
yml multi document mode:
Use in yml - separate different configurations
-
-
profile activation mode
- Configuration file: configure in the configuration file: spring.profiles.active=dev
- Virtual machine parameters: specify in VM options: - Dspring.profiles.active=dev
- Command line parameters: java – jar xxx.jar --spring.profiles.active=dev
Configuration - project internal profile loading order
The loading order is the above arrangement order, and the properties of high priority configuration will take effect
- file:./config /: under the / config directory of the current project
- file:. /: the root directory of the current project
- classpath:/config /: the / config directory of the classpath
- Classpath: /: the root directory of the classpath
Configuration - project external configuration loading order
External configuration files are used to match internal files
1. Command line
java -jar app.jar --name="Spring" --server.port=9000
2. Specify the location of the configuration file
java -jar myproject.jar --spring.config.location=e://application.properties
3. External properties file without profile
classpath:/config/application.properties classpath:/application.properties
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-yzQuEZ1b-1631353027806)(/images/springboot05.png)]
Integrate Junit
-
Build SpringBoot project
-
Introducing starter test dependency
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
- Writing test classes
/** * Test class */ @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootJunitApplication.class ) public class UserServiceTest { @Test public void test(){ System.out.println(111); } }
4. Test
Integrate mybatis
① Build SpringBoot project
② Introduce the start dependency of mybatis and add the mysql driver
<dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--<scope>runtime</scope>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
③ Write DataSource and MyBatis related configuration
application.yml
# datasource spring: datasource: url: jdbc:mysql:///springboot?serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # mybatis mybatis: mapper-locations: classpath:mapper/*Mapper.xml # mapper mapping file path type-aliases-package: com.Huzc.springbootmybatis.domain # config-location: # Specify the core configuration file for mybatis
④ Define tables and entity classes
public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
⑤ Write dao and mapper files / pure annotation development
Write dao
@Mapper @Repository public interface UserXmlMapper { public List<User> findAll(); }
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hzc.springbootmybatis.mapper.UserXmlMapper"> <select id="findAll" resultType="user"> select * from t_user </select> </mapper>
Pure annotation development
@Mapper @Repository public interface UserMapper { @Select("select * from t_user") public List<User> findAll(); }
⑥ Testing
Integrate redis
① Build SpringBoot project
② Introducing redis start dependency
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
③ Configure redis related properties
spring: redis: host: 127.0.0.1 # redis host ip port: 6379
④ Inject RedisTemplate template template
⑤ Write test method, test
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test public void testSet() { //Store data redisTemplate.boundValueOps("name").set("zhangsan"); } @Test public void testGet() { //get data Object name = redisTemplate.boundValueOps("name").get(); System.out.println(name); } }
Automatic configuration - Condition-1
Condition is a conditional configuration interface introduced after spring 4.0. By implementing the condition interface, you can conditionally load the corresponding beans
@Conditional should be used with the implementation class of Condition (ClassCondition)
- ClassCondition
public class ClassCondition implements Condition { /** * * @param context Context object. Used to get environment, IOC container and ClassLoader object * @param metadata Annotation meta object. It can be used to get the attribute value of annotation definition * @return */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { //1. Requirement: create Bean after importing Jedis coordinates //Idea: judge whether the redis.clients.jedis.Jedis.class file exists boolean flag = true; try { Class<?> cls = Class.forName("redis.clients.jedis.Jedis"); } catch (ClassNotFoundException e) { flag = false; } return flag; } }
- UserConfig
@Configuration public class UserConfig { @Bean @Conditional(ClassCondition.class) public User user(){ return new User(); } }
test
@SpringBootApplication public class SpringbootConditionApplication { public static void main(String[] args) { //Start the application of SpringBoot and return to the IOC container of Spring ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args); Object user = context.getBean("user"); System.out.println(user); } }
Automatic configuration - Condition-2
Requirement: the judgment of class is defined as dynamic. Determine which bytecode file exists, which can be specified dynamically.
Custom condition annotation class
import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ClassCondition.class) public @interface ConditionOnClass { String[] value(); }
**Note: * * here @ ConditionOnClass is a custom annotation
@Configuration public class UserConfig { @Bean //@Conditional(ClassCondition.class) @ConditionOnClass("com.alibaba.fastjson.JSON") public User user(){ return new User(); } @Bean @ConditionalOnProperty(name = "hzc",havingValue = "hzc") public User user2(){ return new User(); } }
Test User object creation
@SpringBootApplication public class SpringbootConditionApplication { public static void main(String[] args) { //Start the application of SpringBoot and return to the IOC container of Spring ConfigurableApplicationContext context = SpringApplication.run(SpringbootConditionApplication.class, args); Object user = context.getBean("user"); System.out.println(user); } }
View conditional annotation source code
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hTL4IrzI-1631353027807)(/images/springboot06.png)]
Common condition annotations provided by SpringBoot:
- ConditionalOnProperty: the Bean is initialized by judging whether there are corresponding properties and values in the configuration file
- ConditionalOnClass: judge whether there is a corresponding bytecode file in the environment before initializing the Bean
- ConditionalOnMissingBean: initialize a Bean only after judging that there is no corresponding Bean in the environment
Auto configuration - switch built-in web server
View inheritance diagram
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-OV8lmIwJ-1631353027807)(/images/springboot07.png)]
Exclude Tomcat
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-bCxK7ja9-1631353027808)(/images/springboot08.png)]
Exclusion dependency effect in pom file
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--exclude tomcat rely on--> <exclusions> <exclusion> <artifactId>spring-boot-starter-tomcat</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency> <!--introduce jetty Dependence of--> <dependency> <artifactId>spring-boot-starter-jetty</artifactId> <groupId>org.springframework.boot</groupId> </dependency>
Auto configuration Enable annotation principle
- SpringBoot cannot directly obtain beans defined in other projects
Demo code:
Springboot enable project
/** * @ComponentScan Scanning range: the package and its sub packages of the current boot class * * com.hzc.springbootenable * com.hzc.config * //1.Scan com.hzc.config package using @ ComponentScan * //2.You can use the @ Import annotation to load classes. These classes will be created by Spring and put into the IOC container * //3.The Import annotation can be encapsulated. */ //@ComponentScan("com.hzc.config") //@Import(UserConfig.class) @EnableUser @SpringBootApplication public class SpringbootEnableApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args); //Get Bean Object user = context.getBean("user"); System.out.println(user); } }
- Spring boot enable other is introduced into pom
<dependency> <groupId>com.hzc</groupId> <artifactId>springboot-enable-other</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
Springboot enable other project
- UserConfig
@Configuration public class UserConfig { @Bean public User user() { return new User(); } }
- EnableUser annotation class
import org.springframework.context.annotation.Import; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(UserConfig.class) java public @interface EnableUser { }
Reason: @ ComponentScan scanning range: the package and its sub packages of the current boot class
Three solutions:
1. Use @ ComponentScan to scan the com.hzc.config package
2. You can use @ Import annotation to load classes. These classes will be created by Spring and put into the IOC container
3. The Import annotation can be encapsulated.
Key point: the underlying principle of Enable annotation is to use @ Import annotation to realize dynamic loading of beans
Auto configuration - @ Import details
@The bottom layer of Enable depends on the @ Import annotation to Import some classes. The classes imported with @ Import will be loaded into the IOC container by Spring. While @ Import provides usage in 4:
- Import Bean
- Import configuration class
- Import the ImportSelector implementation class. Generally used to load classes in configuration files
public class MyImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"com.hzc.domain.User", "com.hzc.domain.Role"}; } }
- Import the ImportBeanDefinitionRegistrar implementation class.
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition(); registry.registerBeanDefinition("user", beanDefinition); } }
@The third method is used in EnableAutoConfiguration: @ Import(AutoConfigurationImportSelector.class)
Auto configuration - @ EnableAutoConfiguration details
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-L2mwtnIf-1631353027809)(/images/springboot09.png)]
- @The EnableAutoConfiguration annotation uses @ Import(AutoConfigurationImportSelector.class) internally to load configuration classes.
- Location of configuration file: META-INF/spring.factories. A large number of configuration classes are defined in the configuration file. When the SpringBoot application starts, these configuration classes will be loaded automatically to initialize the Bean
- Not all beans will be initialized. Use Condition in the configuration class to load qualified beans
Auto configuration - Custom starter step analysis
Requirement: customize redis starter. Spring boot is required to automatically create Jedis beans when importing redis coordinates.
Steps:
- Create redis spring boot autoconfigure module
- Create the redis spring boot starter module, which depends on the redis spring boot autoconfigure module
- Initialize Jedis Bean in redis spring boot autoconfigure module. And define the META-INF/spring.factories file
- Introduce a custom redis starter dependency in the test module to test and obtain Jedis beans and operate redis.
Auto configuration - Custom starter implementation - 1
- Create redis spring boot starter project
Redis spring boot autoconfigure is introduced into the pom file
<!--introduce configure--> <dependency> <groupId>com.hzc</groupId> <artifactId>redis-spring-boot-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
- Create redis spring boot autoconfigure configuration project
Create RedisProperties profile parameter binding class
@ConfigurationProperties(prefix = "redis") public class RedisProperties { private String host = "localhost"; private int port = 6379; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
Create RedisAutoConfiguration autoconfiguration class
@Configuration @EnableConfigurationProperties(RedisProperties.class) public class RedisAutoConfiguration { /** * Beans that provide Jedis */ @Bean public Jedis jedis(RedisProperties redisProperties) { return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
Create the META-INF folder under the resource directory and create spring.factories
Note: "\" is used for line feed
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.hzc.redis.config.RedisAutoConfiguration
- Introduce a custom redis starter in the springboot enable project
<!--Custom redis of starter--> <dependency> <groupId>com.hzc</groupId> <artifactId>redis-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
Test in the SpringbootEnableApplication startup class
Jedis jedis = context.getBean(Jedis.class); System.out.println(jedis);
Auto configuration - Custom starter implementation - 2
Test the configuration parameters in application.properties in the springboot enable project
redis.port=6666
Using annotations to complete conditional loading configuration classes
@Configuration @EnableConfigurationProperties(RedisProperties.class) @ConditionalOnClass(Jedis.class) public class RedisAutoConfiguration { /** * Beans that provide Jedis */ @Bean @ConditionalOnMissingBean(name = "jedis") public Jedis jedis(RedisProperties redisProperties) { System.out.println("RedisAutoConfiguration...."); return new Jedis(redisProperties.getHost(), redisProperties.getPort()); } }
event listeners
The event listening mechanism in Java defines the following roles:
- Event: event, an object that inherits the java.util.EventObject class
- Event Source: Source, arbitrary Object
- Listener: listener, an object that implements the java.util.EventListener interface
SpringBoot will call back several listeners when the project is started. We can implement these listener interfaces to complete some operations when the project is started.
- ApplicationContextInitializer
- SpringApplicationRunListener
- CommandLineRunner
- ApplicationRunner
Start time of custom listener: both MyApplicationRunner and MyCommandLineRunner are executed after the project is started, and can be used by putting @ Component into the container
MyApplicationRunner
/** * Execute the run method when the project starts. */ @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("ApplicationRunner...run"); System.out.println(Arrays.asList(args.getSourceArgs())); } }
MyCommandLineRunner
@Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunner...run"); System.out.println(Arrays.asList(args)); } }
To use MyApplicationContextInitializer, add META-INF/spring.factories under the resource folder
org.springframework.context.ApplicationContextInitializer=com.hzc.springbootlistener.listener.MyApplicationContextInitializer
@Component public class MyApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("ApplicationContextInitializer....initialize"); } }
The use of MySpringApplicationRunListener requires adding a constructor
public class MySpringApplicationRunListener implements SpringApplicationRunListener { public MySpringApplicationRunListener(SpringApplication application, String[] args) { } @Override public void starting() { System.out.println("starting...Project startup"); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { System.out.println("environmentPrepared...Prepare environment objects"); } @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.println("contextPrepared...Context object preparation started"); } @Override public void contextLoaded(ConfigurableApplicationContext context) { System.out.println("contextLoaded...The context object starts loading"); } @Override public void started(ConfigurableApplicationContext context) { System.out.println("started...Context object loading completed"); } @Override public void running(ConfigurableApplicationContext context) { System.out.println("running...The project is started and started"); } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { System.out.println("failed...Project startup failed"); } }
Process analysis - initialization
- Configure startup boot class (judge whether there is a startup main class)
- Determine whether it is a Web environment
- Get initialization class and listener class
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-aHMDQFzl-1631353027809)(/images/springboot10.png)]
Process analysis run
- Start timer
- Execution listener
- Prepare environment
- Print banner: you can paste custom banner under resource
- Create context
refreshContext(context);
The Bean is not really created until the refreshContext method is executed
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-l8KXOp6M-1631353027810)(/images/springboot11.png)]
Basic usage of monitor actor
① Import dependent coordinates
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
② Visit http://localhost:8080/acruator
{ "_links":{ "self":{ "href":"http://localhost:8080/actuator", "templated":false }, "health":{ "href":"http://localhost:8080/actuator/health", "templated":false }, "health-component-instance":{ "href":"http://localhost:8080/actuator/health/{component}/{instance}", "templated":true }, "health-component":{ "href":"http://localhost:8080/actuator/health/{component}", "templated":true }, "info":{ "href":"http://localhost:8080/actuator/info", "templated":false } } }
http://localhost:8080/actuator/info
Configure in application.properties
info.name=lucy info.age=99
http://localhost:8080/actuator/health
Turn on health check details
management.endpoint.health.show-details=always
{ "status":"UP", "details":{ "diskSpace":{ "status":"UP", "details":{ "total":159579508736, "free":13558104064, "threshold":10485760 } }, "redis":{ "status":"UP", "details":{ "version":"2.4.5" } } } }
Monitor - the actor enables all endpoint s
Open all endpoint s
Configure in application.properties:
management.endpoints.web.exposure.include=*
Return results of opening all endpoint s:
{ "_links":{ "self":{ "href":"http://localhost:8080/actuator", "templated":false }, "auditevents":{ "href":"http://localhost:8080/actuator/auditevents", "templated":false }, "beans":{ "href":"http://localhost:8080/actuator/beans", "templated":false }, "caches-cache":{ "href":"http://localhost:8080/actuator/caches/{cache}", "templated":true }, "caches":{ "href":"http://localhost:8080/actuator/caches", "templated":false }, "health-component-instance":{ "href":"http://localhost:8080/actuator/health/{component}/{instance}", "templated":true }, "health":{ "href":"http://localhost:8080/actuator/health", "templated":false }, "health-component":{ "href":"http://localhost:8080/actuator/health/{component}", "templated":true }, "conditions":{ "href":"http://localhost:8080/actuator/conditions", "templated":false }, "configprops":{ "href":"http://localhost:8080/actuator/configprops", "templated":false }, "env":{ "href":"http://localhost:8080/actuator/env", "templated":false }, "env-toMatch":{ "href":"http://localhost:8080/actuator/env/{toMatch}", "templated":true }, "info":{ "href":"http://localhost:8080/actuator/info", "templated":false }, "loggers":{ "href":"http://localhost:8080/actuator/loggers", "templated":false }, "loggers-name":{ "href":"http://localhost:8080/actuator/loggers/{name}", "templated":true }, "heapdump":{ "href":"http://localhost:8080/actuator/heapdump", "templated":false }, "threaddump":{ "href":"http://localhost:8080/actuator/threaddump", "templated":false }, "metrics-requiredMetricName":{ "href":"http://localhost:8080/actuator/metrics/{requiredMetricName}", "templated":true }, "metrics":{ "href":"http://localhost:8080/actuator/metrics", "templated":false }, "scheduledtasks":{ "href":"http://localhost:8080/actuator/scheduledtasks", "templated":false }, "httptrace":{ "href":"http://localhost:8080/actuator/httptrace", "templated":false }, "mappings":{ "href":"http://localhost:8080/actuator/mappings", "templated":false } } }
Monitoring - springboot admin graphical interface usage
SpringBoot Admin has two roles, client and server.
The following steps are for creating server and client projects:
admin-server:
- Create admin server module
- Import dependent coordinates admin starter server
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-lrscv35f-163353027810) (/ images / springboot12. PNG)]
<dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-server</artifactId> </dependency>
- Enable monitoring on boot class @EnableAdminServer
@EnableAdminServer @SpringBootApplication public class SpringbootAdminServerApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAdminServerApplication.class, args); } }
admin-client:
- Create admin client module
- Import dependent coordinates admin starter client
<dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> </dependency>
- Configuration related information: server address, etc
# Executive admin.server address spring.boot.admin.client.url=http://localhost:9000 management.endpoint.health.show-details=always management.endpoints.web.exposure.include=*
- Start the server and client services to access the server
SpringBoot deployment
After the SpringBoot project is developed, it supports two ways to deploy to the server:
- jar package (official recommendation)
- war package
Change the packaging method in the pom file to war
Modify startup class
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class SpringbootDeployApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringbootDeployApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(SpringbootDeployApplication.class); } }
Specifies the name of the package
<build> <finalName>springboot</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>