Follow the official documentation to learn SpringBoot 3: spring boot features

 

spring boot features

【Startup related】

 

1. Launch the app

Call SpringApplication's run() in the main method of the startup application class:

public static void main(String[] args) {
	SpringApplication.run(MySpringConfiguration.class, args);
}

 

2. Failed to start

If the application fails to start, FailureAnalyzers will get an error message and a specific solution to the problem.

For example, if port 8080 is occupied, you may see the following message:

***************************
APPLICATION FAILED TO START
***************************

Description:

Embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

 How do I create my own failure analyzer?

1) Create a custom failure analysis class that inherits AbstractFailureAnalyzer. If you can't handle the exception yourself, you can let other implementation classes handle it by returning null;

2) Register the class in the META/spring.factories file as follows:

org.springframework.boot.diagnostics.FailureAnalyzer=\
com.example.ProjectConstraintViolationFailureAnalyzer

 If you need to access BeanFactory or Environment, the custom FailureAnalyzer can implement BeanFactoryAware or EnvironmentAware interface.

 

3. Custom Banner

Banner, the image when the application starts, defaults to spring boot:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::   v2.0.0.RELEASE

 Specify the file location by adding a banner.txt to the classpath (eg in the resources folder) or by setting the spring.banner.location property in the configuration file. If the encoding of the file is not UTF-8, you need to set spring.banner.charset to specify the encoding.

 

In addition to adding text files, you can also add banner.gif, banner.jpg or banner.png pictures, or set the spring.banner.image.location property to specify the file location, and the pictures will be converted to ASCII code for printing.

The blogger added banner.png under resources:

 

After launching the application, the effect is displayed:

 

 

Extension: what is classpath?

Although the word classpath is translated into Chinese, everyone knows it is called "classpath", so what exactly is a classpath? Presumably many of my classmates have been troubled like me.

classpath refers to the directory where classes (bytecode files of classes) are located after the program is compiled . Before the program is compiled, usually the .java file is placed in the java folder (such as src/main/java/service/UserService.java), and the configuration file is usually placed in the resources folder (such as src/main/resources/application. properties). When the program is compiled, the .java file in the java folder will become the .class file in the target/classes folder, and the files in the resources folder will also be placed in the classes folder. The classes folder at this time is The classpath of the project.

 

If you put banner.txt or banner.png directly in the src/main/java folder, it will not take effect because it is not in the target/classes folder after compilation. (The files compiled by the IntelliJ IDEA tool are in the target directory)

 

4. Customize SpringApplication

When you feel that the default SpringApplication is not enough, you can customize it by creating a local (as opposed to spring-boot-starter) instance.

For example, the custom Banner in the previous section can also be implemented programmatically:

public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Example.class);
        application.setBanner(new MyBanner());
        application.run(args);
}

 It can also be turned off:

public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Example.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
}

 

5. Streaming API

Through the SpringApplicationBuilder object, it is possible to chain invocation of multiple methods and create a hierarchical application context:

new SpringApplicationBuilder()
		.sources(Parent.class)
		.child(Application.class)
		.bannerMode(Banner.Mode.OFF)
		.run(args);

 There are some restrictions to be aware of when creating hierarchical application contexts, such as web components must be contained in child contexts, and child contexts and parent contexts must use the same Environment.

 

6. Events and listeners

Some events are fired before the ApplicationContext is created, so it is not possible to register the listener as a @Bean on these events. It can be registered through the SpringApplication.addListeners() or SpringApplicationBuilder.listeners() methods; if you want these listeners to be registered automatically, regardless of how the application is created, you can add the META-INF/spring.factories file and register the listeners through the following example :

org.springframework.context.ApplicationListener=com.example.project.MyListener

 

7. Web Environment

SpringApplication will try to create the correct type of ApplicationContext, by default using AnnotationConfigApplicationContext or AnnotationConfigServletWebServerApplicationContext,

This is based on whether or not a web application is being developed. The algorithm for determining whether an environment is a web environment is fairly simple, based on the existence of a few classes. If you want to override the way it determines the environment type,

Can be set via setWebEnvironment(boolean webEnvironment). You can control the ApplicationContext yourself by calling the setApplicationContextClass() method. When using SpringApplication in a JUnit test environment, it is recommended to call the setWebEnvironment(false) method.

 

8. Access application parameters

If you need to access the arguments passed into the SpringApplication.run() method, you can inject an org.springframework.boot.ApplicationArguments bean. The ApplicationArguments interface provides access to native String[] arguments and arguments parsed as option and non-option as follows:

 

import org.springframework.boot.*
import org.springframework.beans.factory.annotation.*
import org.springframework.stereotype.*

@Component
public class MyBean {

	@Autowired
	public MyBean(ApplicationArguments args) {
		boolean debug = args.containsOption("debug");
		List<String> files = args.getNonOptionArgs();
		// if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
	}

}
 Spring Boot also registers a CommandLinePropertySource with the Spring environment. This makes it possible to inject individual application parameters by using the @Value annotation.

 

 

9 Use ApplicationRunner or CommandLineRunner

If there is some special code that needs to be run before the SpringApplication is started, it can be done by implementing the ApplicationRunner or CommandLineRunner interface. Both interfaces work the same way,

And provide a single run method, the run method will be called before SpringApplication.run() completes.

 

The CommandLineRunner interface accesses application parameters as a simple string array, as in the following example:

 

import org.springframework.boot.*
import org.springframework.stereotype.*

@Component
public class MyBean implements CommandLineRunner {

	public void run(String... args) {
		// Do something...
	}

}
 If multiple CommandLineRunner or ApplicationRunner beans are defined, they must be called in a specific order.

 

Order invocation can be done by additionally implementing the org.springframework.core.Ordered interface, or by using the org.springframework.core.annotation.Order annotation.

 

10. Exit the app

Every SpringApplication registers a shutdown hook with the JVM to ensure that the ApplicationContext is gracefully closed on exit. All Spring standard lifecycle callbacks can be used, such as the DisposableBean interface or the @PreDestroy annotation.

 

Additionally, if you wish to execute a specific exit code before SpringApplication.exit() is called, these beans can do so by implementing the org.springframework.boot.ExitCodeGenerator interface.

These specific exit codes are passed to System.exit() to be returned as status codes, as in the following example:

@SpringBootApplication
public class ExitCodeApplication {

	@Bean
	public ExitCodeGenerator exitCodeGenerator() {
		return () -> 42;
	}

	public static void main(String[] args) {
		System.exit(SpringApplication
				.exit(SpringApplication.run(ExitCodeApplication.class, args)));
	}

}

 Moreover, the exception class can return the exit code when an exception occurs by implementing the ExitCodeGenerator interface and the getExitCode() method.

 

11. Administrator Features

Enable (disable) admin-related features by specifying the spring.application.admin.enabled property to true (false), which exposes the SpringApplicationAdminMXBean to the MBeanServer platform. Spring boot applications can be managed remotely by using this feature, which is useful for service wrapper implementations.

 

 

[External placement]

 

Springboot can externalize configuration so that the same code can be adapted to different environments. Simply put, it is to get the specified value from an external configuration file without writing dead code.

Use properties files, YAML files, environment variables, and command-line parameters for configuration. These configured property values ​​can be injected directly into beans through the @Value annotation, and can be accessed through Spring's Environment interface implementation class.

Or bind to structured objects via @ConfigurationProperties.

 

In order to achieve reasonable coverage of property values ​​(because there are multiple configuration methods, there may be duplicate key value coverage), springboot uses a special order. Properties will be read in the following order:

1. Devtools global settings. (Configured in ~/.spring-boot-devtools.properties when devtools is enabled)

2. The property value in the @TestPropertySource annotation in the test class

3. In the test class @SpringBootTest#properties 注解中的属性值

4. Command Line Parameters

5. Property value of SPRING_APPLICATION_JSON (JSON embedded in environment variable or system property)

6. ServletConfig initialization parameters

7. ServletContext initialization parameters

8. JNDI properties from java:comp/env

9. Java system property values ​​(values ​​obtained through System.getProperties())

10. Operating System Environment Variables

11. RandomValuePropertySource has property values ​​and conforms to random.* format

12. Profile-specific application properties that are not entered into the jar package (application-{profile}.properties and YAML variables)

13. Application properties entered into the jar package (application-{profile}.properties and YAML variables)

14. Application properties that are not entered into the jar package (application-{profile}.properties and YAML variables)

15. Application properties entered into the jar package (application-{profile}.properties and YAML variables)

16. @PropertySource annotated properties on @configuration classes

17. Default properties (specified by setting SpringApplication.setDefaultProperties)

 

Before giving specific examples, it is recommended to write a component (@Component) that uses the value of the name attribute, as follows:

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

 Add a "application.properties" property file to the classpath (such as the resources resource folder) and specify the value of name in the file, such as name=Lina.

 For one-off tests, it can be specified on the command line, for example:

java -jar app.jar --name="Spring"
 

 

The property values ​​of SPRING_APPLICATION_JSON can be applied to the command line by means of environment variables:

1. The following commands can be used in a UNIX shell:

$ SPRING_APPLICATION_JSON='{"acme":{"name":"test"}}' java -jar myapp.jar
 This command indicates that the property value corresponding to acme.name in spring is test.

 

2. Use JSON as spring.application.json in System property:

 

$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar
        3. Use JSON by using command line arguments:
$ java -jar myapp.jar --spring.application.json='{"name":"test"}'
        4. Use JSON as a JNDI variable:
java:comp/env/spring.application.json
         1. Configure random property values ​​RandomValuePropertySource is useful for injecting random values. It can generate integers, longs, uuids, or strings:
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
  2. Access command line property values      

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326108825&siteId=291194637