springBoot Feature Compilation (Basic)

Posted by sfmnetsys on Sun, 30 Jan 2022 21:38:31 +0100

1. Customize SpringApplication

Customize bannnr

public static void main(String[] args){
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setShowBanner(false);
app.run(args);
}

Smooth API building

new SpringApplicationBuilder()
.showBanner(false)
.sources(Parent.class)
.child(Application.class)
.run(args);

Time and monitoring


Event listeners can be registered in a variety of ways, most commonly using SpringApplication.addListeners(...) method. Apply things while your app is running
Messages will be sent in the following order:
1. An ApplicationStartedEvent is sent at the beginning of the run, but before any processing other than listener registration and initialization.
2. An ApplicationEnvironmentPreparedEvent is sent before the context is created, although the Environment will be used in a known context.
3. Before refresh starts, but after the bean definition has been loaded, an ApplicationPreparedEvent is sent.
4. If an exception occurs during startup, an ApplicationFailedEvent will be sent.

web Environment

By default, use
AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext depends on whether you are developing a web
Apply.
The algorithm used to determine a web environment is fairly simple (based on the existence of certain classes). If you need to override the default behavior, you can use
setWebEnvironment(boolean webEnvironment). By calling setApplicationContextClass(...), you have full control
The type of the ApplicationContext.
Note: When SpringApplication is used in a JUnit test, it is advisable to call setWebEnvironment(false).

Command Line Start

If you want to get the original command line parameters, or once SpringApplication starts, you need to run some specific code, you can implement
CommandLineRunner interface. The run(String...args) method will be called on all Spring beans that implement the interface.

import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}


If some CommandLineRunner beans are defined to have to be called in a specific order, you can implement an additional org.springframework.core.Ordered connection
Or use org.springframework.core.annotation.Order comment.

Sign out

Each SpringApplication will register a shutdown hook for the JVM to ensure that the ApplicationContext is gracefully closed when it exits. All Standard
Spring life cycle callbacks, such as the DisposableBean interface or the @PreDestroy annotation, can be used.
Additionally, if beans want to return a specific exit code at the end of the application, it can
org.springframework.boot.ExitCodeGenerator interface
 

2. Externalized Configuration Use


Spring Boot uses a very special PropertySource order to allow for a reasonable override of values, requiring the following order of attributes to be considered:
1. Command Line Parameters
2. JNDI properties from java:comp/env
3. Java System Properties (System.getProperties())
4. Operating system environment variables
5. Only in random. * The properties contained in the result in a RandomValuePropertySource
6. Application configuration files (application.properties, including YAML and profile variables) outside the packaged jar
7. Application configuration files (application.properties, including YAML and profile variables) within the packaged jar
8. The @PropertySource annotation on the @Configuration class
9. Default properties (specified using SpringApplication.setDefaultProperties)

Configure Random Values

RandomValuePropertySource is useful when injecting random values, such as keys or test cases. It can produce integers, longs, or strings, such as:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}


Random. The int* syntax is OPEN value (,max) CLOSE, where OPEN, CLOSE can be any character, and value, Max is an integer. If provided
max, then value is the minimum value, max is the maximum value (excluded)

Command Line Properties

By default, SpringApplication converts any optional command line parameter (starting with'--', for example, --server.port=9000) to property and converts it to property
Add to Spring Environment. As mentioned above, command line attributes always take precedence over other attribute sources.
If you don't want to add command line properties to your Environment, you can use SpringApplication.setAddCommandLineProperties(false) to disable
Stop them.

Application Properties File

SpringApplication will load the application from the following location. Properrties files and add them to the Spring Environment:
1. A/config subdirectory in the current directory
2. Current Directory
3. A/config package under classpath
4. classpath root
This list is sorted by priority (the higher position in the list will cover the lower position).
Note: You can use the YAML ('.yml') file instead of'. properties'.
If you don't like to apply. As a configuration file name, you can specify spring.config.name environment property to switch other names. You too
You can use spring. Config. The location environment property refers to an explicit path (a comma-separated list of directory locations or file paths).

$ java -jar myproject.jar --spring.config.name=myproject
//or
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties


If spring.config.location contains directories (as opposed to files), which should end with / before loading (names generated by spring.config.name will be appended)
Add to the back). Regardless of spring. Config. What is the value of location, the default search path classpath:,classpath:/config,file:,file:config/is always used.
In this way, you can apply. Set a default value for the application in properties, then overwrite it with a different file when running, while leaving the default
To configure.
Note: Most operating systems do not allow period-separated key names if you use environment variables instead of system configuration, but you can
Use underscores instead (for example, SPRING_CONFIG_NAME instead of spring.config.name). If your application runs on one
In containers, JNDI properties (java:comp/env) or servlet context initialization parameters can be used instead of environment variables or system properties, or
Using environment variables or system attributes

Property Placeholder

app.name=MyApp
app.description=${app.name} is a Spring Boot application

Property Profile Loading

The Spring framework provides two convenient classes for loading YAML documents, and YamlPropertiesFactoryBean loads YAML as a Properties.
YamlMapFactoryBean loads YAML as a Map.

Note: yaml files cannot be loaded with the @PropertySource annotation as properties files do

Special usage:

The YAML list is represented as using [index] indirect references as attribute keys, such as the following YAML:
my:
servers:
- dev.bar.com
- foo.bar.com
This will be translated into the following properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

Configuration Properties for Type Security

Even with the @ConfigurationProperties annotation, it works well with external profiles;

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private InetAddress remoteAddress;
// ... getters and setters
}
# application.yml
connection:
username: admin
remoteAddress: 192.168.1.1
# additional configuration as required

How to use:

@Service
public class MyService {
@Autowired
private ConnectionSettings connection;
//...
@PostConstruct
public void openConnection() {
Server server = new Server();
this.connection.configure(server);
}
}

You can quickly register @ConfigurationProperties bean s by simply listing attribute classes in the @EnableConfigurationProperties comment
Definition.
 

@Configuration
@EnableConfigurationProperties(ConnectionSettings.class)
public class MyConfiguration {
}

Third party configuration

When you need to bind an attribute to a third one that is not under your control
This is very useful when square components are used.
To configure a bean from the Environment property, add @ConfigurationProperties to its bean registration process:

@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
...
}


As with the ConnectionSettings example above, any property definition prefixed with foo is mapped to the FooComponent.

Loose Binding

Spring Boot uses some relaxed rules to bind the Environment property to @ConfigurationProperties beans, so the Environment property name and
bean attribute names do not need to match exactly. Common examples useful include dashed line splitting (for example, context--path bound to contextPath) and turning environment attributes into
Bind port for uppercase letters (for example, PORT).
Example:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {
private String firstName;
}

The following property names can be used for the @ConfigurationProperties class above:
attribute
Explain
person.firstName
Standard Hump Rules
person.first-name
Dotted line representation, recommended for. properties and. yml file
PERSON_FIRST_NAME
Uppercase, recommended when using system environment variables

Spring tries to force external application properties to be of the correct type when bound to @ConfigurationProperties beans. If a custom type conversion is required, you
You can provide a ConversionService bean (bean id is conversionService) or a custom property editor (via a
CustomEditorConfigurer bean).

@ConfigurationProperties check

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}

You can also add a custom Spring Validator by creating a bean called configurationPropertiesValidator.
Note: The spring-boot-actuator module contains an endpoint that exposes all @ConfigurationProperties beans. Simply point your web browser at
To/configprops or use an equivalent JMX endpoint.

Profiles

Spring Profiles provides a way to isolate application configurations and make them work only in specific environments. Any @Component or
The @Configuration can be marked with @Profile to limit when it is loaded.

@Configuration
@Profile("production")
public class ProductionConfiguration {
// ...
}

Or use the command line: --spring.profiles.active=dev,hsqldb

Profiles Activation

Spring. Profiles. The active attribute follows the same arrangement rules as other attributes, and the highest PropertySource wins. That is, you can use the
Application. Specify valid configurations in properties and replace them with command line switches.
Sometimes it is useful to add specific configuration properties to the active configuration rather than replace them. spring.profiles.include property can be used to add unconditionally
Effective configuration. The entry point to SpringApplication also provides a Java API for setting additional configurations (for example, in those that pass
Spring. Profiles. Configuration above which the active property takes effect: Refer to the setAdditionalProfiles() method.
Example: When an application uses the following properties and uses --spring. Profiles. If the active=prod switch is running, the proddb and prodmq configurations will also take effect:
---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include: proddb,prodmq
Note: spring. The profiles property can be defined in a YAML document to determine when the document is included in the configuration.

You can also call SpringApplication.setAdditionalProfiles(...) method that programmatically sets the effective configuration. Use
Spring's Configurable Environment interface excitation configuration is also possible.

Journal

The Spring Boot internal logging system uses Commons Logging, but opens the underlying logging implementation. By default, Spring Boot only logs to the console, not to the log file.

Open the console's DEBUG-level logging with the--debug identity.

If your terminal supports ANSI, color log output will be used to increase readability. You can set spring.output.ansi.enabled is a supported value to override automatic detection

By adding the appropriate libraries to the classpath, various log systems can be activated. Then in the root directory of the classpath or through the Spring Environment
Logging. The location specified by the config property provides a suitable configuration file for further customization (note that the log was created in the ApplicationContext
Initialized before build, so it is not possible to control the log through @PropertySources in Spring's @Configuration file. System attributes and normal
The Spring Boot external configuration file is working properly).

3. Automatic Configuration

Automatic configuration adds the following features:
1. Introduce ContentNegotiating ViewResolver and BeanNameViewResolver beans.
2. Support for static resources, including WebJars.
3. Automatically register Converter, GenericConverter, Formatter beans.
4. Support for HttpMessageConverters.
5. Automatically register MessageCodeResolver.
6. For static index. Support for html.
7. Support for custom Favicon s.
If you want full control over Spring MVC, you can add your own @Configuration and annotate it with @EnableWebMvc. If you want to keep Spring
Boot MVC features, and simply adds other MVC configurations (interceptors, formatters, view controllers, etc.), you can add your own WebMvcConfigurerAdapter type @Bean (without the @EnableWebMvc annotation).

4,HttpMessageConverter

Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses. A reasonable default value is included just right (out of the box), for example
Objects can be automatically converted to JSON (using the Jackson library) or XML (using Jackson XML extensions if they are available, or JAXB if they are not). Character string
UTF-8 encoding is used by default.
If you need to add or customize converters, you can use Spring Boot's HttpMessageConverters class:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
@Configuration
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}
}

Any HttpMessageConverter bean s that appear in the context will be added to the converters list, and you can override the default converters in this way.

The main methods of this interface are as follows:

boolean canRead(Class<?> clazz, MediaType mediaType);
boolean canWrite(Class<?> clazz, MediaType mediaType);
List<MediaType> getSupportedMediaTypes();
T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
void write(T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;

Data transformation in source code defaults to the following:

protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
		StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
		stringConverter.setWriteAcceptCharset(false);

		messageConverters.add(new ByteArrayHttpMessageConverter());
		messageConverters.add(stringConverter);
		messageConverters.add(new ResourceHttpMessageConverter());
		messageConverters.add(new SourceHttpMessageConverter<Source>());
		messageConverters.add(new AllEncompassingFormHttpMessageConverter());

		if (romePresent) {
			messageConverters.add(new AtomFeedHttpMessageConverter());
			messageConverters.add(new RssChannelHttpMessageConverter());
		}

		if (jackson2XmlPresent) {
			ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().applicationContext(this.applicationContext).build();
			messageConverters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper));
		}
		else if (jaxb2Present) {
			messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
		}

		if (jackson2Present) {
			ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build();
			messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper));
		}
		else if (gsonPresent) {
			messageConverters.add(new GsonHttpMessageConverter());
		}
	}

The default method is called only when no customization is available:

protected final List<HttpMessageConverter<?>> getMessageConverters() {
		if (this.messageConverters == null) {
			this.messageConverters = new ArrayList<HttpMessageConverter<?>>();
			configureMessageConverters(this.messageConverters);
			if (this.messageConverters.isEmpty()) {
				addDefaultHttpMessageConverters(this.messageConverters);
			}
			extendMessageConverters(this.messageConverters);
		}
		return this.messageConverters;
	}

customization
Null value handling
The data requested and returned has many null values, which are sometimes meaningless and can be filtered out and not returned, or set to default values. For example, by overriding the getObjectMapper method, null values returned are not serialized:

converters.add(0, new MappingJackson2HttpMessageConverter(){
    @Override
    public ObjectMapper getObjectMapper() {
        super.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
                return super.getObjectMapper();
    }
}


XSS script attack
To ensure that the input data is more secure and to prevent XSS script attacks, we can add a custom deserializer:

//Correspondence cannot return String type directly
converters.add(0, new MappingJackson2HttpMessageConverter(){
    @Override
    public ObjectMapper getObjectMapper() {
        super.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

                // XSS script filtering
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(String.class, new StringXssDeserializer());
        super.getObjectMapper().registerModule(simpleModule);

        return super.getObjectMapper();
    }

Summarize the various MediaType s and JavaType s supported by the common HttpMessageConverter and their corresponding relationships here:

Class Name Supported JavaType Supported MediaType
ByteArrayHttpMessageConverter    byte[]    application/octet-stream, */*
StringHttpMessageConverter    String    text/plain, */*
MappingJackson2HttpMessageConverter    Object    application/json, application/*+json
AllEncompassingFormHttpMessageConverter    Map<K, List<?>>    application/x-www-form-urlencoded, multipart/form-data
SourceHttpMessageConverter    Source    application/xml, text/xml, application/*+xml
 

 

 

 

 

 

 

 

 

 

 

Topics: Spring Boot