Moment For Technology

SpringBoot basis

Posted on Aug. 8, 2022, 7:54 p.m. by 孫中山
Category: The back-end Tag: The back-end

Introduction to a,

1. Write a basic SpringBoot project

1. Create maven project

2. Import dependencies

3. Write the main program

@springBootApplication public class MainApplication {public static void main(String[] Run (mainApplication.class, args); }}Copy the code

2. HelloWorld inquiry

1. POM files

1. Parent project
parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version1.5.9.RELEASE/version /parent Its parent project is spring-boot-dependecies: To really manage all the dependent versions of a Springboot application there is a propertes that defines the version of each dependencyCopy the code

SpringBoot version arbitration center

By default, you do not need to write versions for future import dependencies; Versions not introduced in dependecies need to be declared

2. Scenario initiator
spring-boot-stater-web
Copy the code

Spring - the boot - stater:

An initiator in the SpringBoot scenario, which declares dependency imports to import components required by the normal running of web templates

SpringBoot pulls all the functional scenarios together as "starters", only importing dependencies on those scenarios into the project. Versions are automatically controlled by the parent POM. Each function corresponds to a scenario initiator

2. Main program class

@springBootApplication public class MainApplication {public static void main(String[] args) SpringApplication.run(MainApplication.class, args); }}Copy the code

The class annotated by @SpringBootApplication is the main configuration class for SpringBoot, which runs the main method to start the application

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
Copy the code

1. @SpringBootConfiguration: indicates the SpringBootConfiguration class. The underlying @Configuration Configuration class = Configuration file

2. @enableAutoConfiguration: Enable the automatic configuration function. Is a composite annotation

@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
Copy the code

1. @autoConfigurationPackage

Scan the package of the main configuration class and all the components in all the subpackages below into the Spring container

2, @ Import ({AutoConfigurationImportSelector. Class}) : to Import a component container; The imported components by AutoConfigurationImportSelector. Class (import component selector) specified.

AutoConfigurationImportSelector. Class under the class of String [] selectImports () method, all you need to import the component class name to return, these components can be added to the container. Will import a lot of autoconfiguration classes into the container (xxxAutoConfiguration)

Todo Screenshot automatic configuration

AutoConfigurationImportSelector. GetCandidateConfigurations () method -  SpringFactoriesLoader. LoadFactoryNames () : From the "meta-INF /spring.factories" path, Spring - the boot - autoconfiguration package under the meta-inf/spring. Factories defined inside the file org. Springframework. Boot. Autoconfigure. EnableAutoConfigu Automatic configuration takes effect when a configuration class defined in a ration field is imported to a containerCopy the code

3. Use Spring Initializer to quickly create projects

Select the module you need, the network automatically download dependencies

The default generated content:

  • The main program is already generated, so there is no need to write the Application class manually

  • Resources folder.

    • Static: Save all static resources: imags...
    • Templates: Store all template pages, default JAR package, embedded Tomcat, JSP pages are not supported by default, you can use a template engine (freemarker, Thymeleaf)
    • Application. properties: configuration file of the Spring Boot application. Ex: server.port=XXX

Configuration file

1. Configuration files

SpringBoot uses a global configuration file

  • application.properties
  • application.yml

Effect: Changes the default value of automatic configuration

YAML(YAML Ain't Markup Language) : Data-centric configuration

  • A: It's a markup language
  • Isn't: Isn't a markup language

Markup language:

Yml configuration example

server:
  port: 8090
Copy the code

2. YAML syntax

1. Basic grammar

K: [space]V indicates a key-value pair

The hierarchy is controlled by indented Spaces. The left - aligned column is the same hierarchy

Properties and values are also case-sensitive

2, value writing

Literals: ordinary values (numbers, strings, booleans)

  • K: v: the literal value is written directly, and the string is not quoted by default
  • "" : does not escape special characters in the string
  • ": will escape special characters

Object: attribute + value, key-value pair

  • K: v: The next line writes the properties and values of the object
Friends: lastName: zhangsan age: 20Copy the code
  • Inline writing

    friends: {lastName:zhangsan, age: 18}
    Copy the code

Array:

Represents an element in an array with a - value

pets:
 - cat
 - dog
 - pig
 
pets: [cat,dog,pig]
Copy the code

3. Obtain the configuration file value

@ConfigurationProperties(prefix = "XXX ") : Bind all properties in this class to values in the configuration file

2. Import the configuration file processor

spring-boot-configuration-processor

Unit testing

@SpringBoottest: Unit tests using SpringBoot

@runwith (springrunner.class) : drive

3. Properties configuration file

1, grammar,

2. Obtain the configuration file value

@configurationProperties (prefix = "XXX "); Encoding problem: FileEncodings: Set conversion to ASCII

2. @value: Spring's underlying annotation that assigns values to fields. @value (${xxx.yyy}/ expression/literal)

Get the map value:

@ConfigurationProperties @Value
function Import the property definition of a class Import of a single field
Loosely bound last-name=lastName Does not support
spEl Does not support support
Complex type encapsulation support Does not support

When mapping javabeans to configuration files -@ConfigurationProperties

Get the configuration Value for a single field - @value

Third, the Profile

Used to support multiple environment configurations

1. Multiple Profile files

1. Properties file

The name of the main profile can be application-{profile}.properties/yaml

2. Yaml files

-- : Separate documents in the same file

2. Activate the specified profile

  • Spring-profiles.active = XXX: indicates the activation of the specified profile in the profile
  • Command line: idea runtime specified. - spring. Profiles. The active = dev. Higher priority
  • Jar the project into a jar package (the finished package is in the target directory) with Java -jar xxx.jar --spring.profiles. Active = dev
  • Vm parameters. The VM options: - Dspring - profiles. The active = dev

Four, logs,

1. Logging framework

JUL, JCL, jboss-Logging, logback, log4j, log4j2, slf4J....

Log facade (Abstraction layer) The logging implementation
JCL, SLF4j,jboss-logging Log4j,JUL, Log4j2, LogBack

Choose a facade on the left and an implementation on the right

Log store: slf4J; Implementation: log4j2

Spring is the Spring framework. Spring is JCL by default, and SlF4J and LogBack are used for SpringBoot

2. Use SLF4J

Import slF4jJAR and logback implementation jars

import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); }}Copy the code

Each logging implementation framework has its own configuration file. With SLF4J, the configuration file is still made into the logging implementation framework configuration file.

How do I unify all logs on my system to SLF4J: there is A transformation JAR (A-over-B.jar) package to import

1. Exclude the log framework of the system

2. Replace the old logging framework with a tundish

3. Import the actual slF4J implementation package

3. SpringBoot log relationship

dependency
  groupIdorg.springframework.boot/groupId
  artifactIdspring-boot-starter-logging/artifactId
/dependency
Copy the code

In SpringBoot, a variety of XX-over-SLF4J packages are imported at the bottom layer of Spring-boot-start-logging, and the log abstraction layer SLF4J is imported at the bottom layer. Other logs are converted to SLF4J and logged using logback

If you introduce another framework, be sure to remove that framework's default logging dependency

SpringBoot automatically ADAPTS all logs, and slF4J-logback is used to record logsWhen introducing other frameworks, log dependencies need to be removed. Logging is configured by default and can be used directly.

/** * Generates a logger. Logger = loggerFactory.getLogger (getClass()); LoggerFactory = loggerFactory.getLogger ()); Logger.trace (); Logger.debug (); // Debug information, debug key output logger.debug(); // SpringBoot defaults to the info level and above // Common information output logger.info(); / / warning logger. Warn (); // Error logger. Error ();Copy the code

Logging.file =XXX // Do not specify a path to generate logging.path=YYY under the current projectCopy the code

Spring. log is the default log file name when file is not specified

Log Output format

PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %t %-5level %logger{30}.%method - %msg%n" /
Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.