spring
Understanding spring
spring
How to manageBean
(Core idea: Dependency injection)
registeredBean
- registered
Bean
: the equivalent ofnew
A Java class —–Independent withdrawal dependency - Common comments:
@Bean
,@Component
,@Controller
,@Service
,@Repository
assemblyBean
- assembly
Bean
: equivalent to callingnew
The resulting Java class to use it; Assembly by type is implemented due to Java polymorphismIOC
—–dependent - Common notes:
@Autowired
understand
The registered Bean will be stored in the Spring container, and when the Bean is assembled, the appropriate Bean new instance will be taken from the Spring container (by type, by name) for use.
By assembling beans according to type, Java polymorphism can be flexibly used to achieve IOC.
MVC
thought
Controller
The controller
How to get SpringMVC request parameters
- Return body customization:
ResponseEntity
Commonly used annotations
Spring has a built-in list of common comments
Project main entry notes
@SpringBootApplication
Equivalent to the following three notes:
-
@enableAutoConfiguration: Enables the automatic configuration mechanism of Spring Boot. So the following @enablexxx is optional in Spring Boot:
A. Includes: @enableAspectJAutoProxy; Registered beans in the container can use AOP, and registered beans can implement AOP using @aspect, @pointcut, @around, and so on. Java – Spring AOP Works without @enableAspectJAutoProxy – Stack Overflow)
B. Includes: @enableWebMVC: a Bean registered in a container can be used as an interceptor so that it can be injected with implements WebMvcConfigurer
C. Includes: @enableAsync: Beans registered in the container can use asynchronous multithreading
The registered Bean can then use @async to execute asynchronous functions
Spring Boot
How to use multithreading elegantlyD. Included: @enablesCheduling: Beans registered in a container can use scheduled tasks
This allows registered beans to execute Scheduled task functions using @scheduled
Spring Boot
How to use scheduled tasks elegantlyE. includes: @ EnableTransactionManagement: vessel registered in Bean can use transaction
This registered Bean can then execute transactions using @Transactional
Spring Boot
How to gracefully use transaction managers and create transaction managers for multiple data sources -
@ComponentScan: Scans beans annotated by @Component. By default, annotations scan all classes in the package in which that class is located
Includes: @ MapperScan, @ Mapper, @ Repository can not write, because in the application. The yml path configured in the Mapper interfaces
-
@Configuration: Allows registering additional beans or importing additional Configuration classes in the Spring context
registeredBean
And assemblyBean
-
There are two ways to register beans:
@Component: decorator class; Each @bean inside is a new instance of @Configuration each time it is called: the decorator class is a special @Component; @bean: a comment that decorates a class in the three-tier schema of member methods in classes annotated by @Component / @Configuration (default singleton): @Controller(presentation layer), @Service(business layer), @Repository(persistence layer)
@restController equals @Controller + @responseBody
Spring
@Configuration
和@Component
The difference between)@scope (···) : singleton: a unique bean instance. Beans in Spring are singleton by default. Prototype: Each request creates a new bean instance. Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request. Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.
@profile (···): Specifies the Bean to be registered under environment variables
@mapper: Mybatis annotation to register beans in the Spring container; Equivalent to scanning the file path @mapperscan on the startup class;
Note: You need to add the path of the XML file that writes the Mapper layer to mybatis mapper-locations and configure the Entity class path myBatis typeAliasesPackage in the configuration file application.yml
Persistence layer registration assembly process: Spring will scan all mapper layer XML based on mybatis mapper-locations in the configuration file and find the DAO interface based on the fully qualified package name that uses namespace in mapper layer XML. Each member method in the DAO interface generates a new DAO class Bean. The type of the new DAO class Bean is DAO interface name, and the name of the DAO interface is lowercase. Finally, register the new DAO class Bean with the Spring container; When the Service layer finds the new DAO class Bean via @Resource and injects it, the entire persistence layer is strung together.
Scanning interface paths: add @mapper <==== to each DAO interface class, equivalent to ====> use @Mapperscan on startup classes or custom Mybatis configuration classes. You can choose one or neither; Because as long as the Spring container scans the XML file, the XML file can find the DAO layer interface through namespace.
Configure the member methods of each DAO class to implement the class XML path: Mybatis mapper-locations in the configuration file application.yml
Mybatis typeAliasesPackage in the configuration file application.yml; Fully qualified names rather than alias are recommended
Why not write @mapper
-
From the Spring library: @autoWired default assembly by type, @autowired + @Qualifier(···) assembly by name; From the Java standard: @ the Resource (name = “… “) by name by default assembly, @ the Resource (type = “… “)
Note: Usually annotated assembly beans are injected directly into member variables, equivalent to setter injection.
Spring boot
Inject a class with multiple constructors into a bean container and implement four methods to distinguish beans with different bean names for the same class
The Spring Boot annotation assembly can only use the no-parameter constructor. If you need to inject a Bean with a parameter constructor, you can do so by using new getApplicationContext().getBean(clazz)(·· parameter ··).
Spring doesn’t have the flexibility to inject parameterized constructor solutions with annotations
Request the relevant
- Request method annotation:
@ GetMapping (…), @ PostMapping (…), @ PutMapping (…), @ DeleteMapping (…), @ PatchMapping (…); @ RequestMapping (value = “… “, method = RequestMethod. POST) 2. @pathVariable, @requestParam, @requestBody (instead of @modelAttribute)
Request parameter verification
Reading configuration Files
@EnableConfigurationProperties
PropertySource: Specifies the configuration file to use
@ ConfigurationProperties: @ ConfigurationProperties (prefix = “… “)
Global exception handling
@ControllerAdvice
RestControllerAdvice(define global exception handling class): equivalent to @ControllerAdvice + @responseBody @ExceptionHandler(write the type of exception you want to block)
Explanation: Classes annotated by @RestControllerAdvice are automatically injected into the controller’s request method annotation (@RequestMapping)
Spring exception Handling
Transaction processing
Transactional(rollbackFor = exception.class)
JSON
otherSpring
Related note
-
@ EnableXXX: Used with @Configuration, Including @ EnableAsync, @ EnableScheduling, @ EnableTransactionManagement, @ EnableAspectJAutoProxy, @ EnableWebMvc. Usually Spring Boot does not need to be configured; the framework is already configured
-
Lazy: Spring does not instantiate the bean until it is used
Annotations to the Lombok library
doubt
@beans are used for registration of third-party components
Spring MVC relevant
Spring’s life cycle
When the instantiated Bean is startedBeanPostProcess
- Spring instantiates the Bean (equivalent to new Xx() in the program)
- Spring injects the value and a reference to the Bean into the Bean’s corresponding properties
- If the Bean implements the BeanNameAware interface, Spring passes the Bean ID to the setBeanName() method.
- If the Bean implements the BeanFactoryAware interface, Spring calls the setBeanDactory(BeanFactory BF) method and passes in the BeanFactory container instance as an argument. (The main purpose of implementing BeanFactoryAware is to fetch Spring containers, such as beans publishing events through Spring containers, etc.)
- If the Bean implements the ApplicationContextAwaer interface, the Spring container calls the setApplicationContext(ApplicationContext CTX) method, The Spring container calls the setApplicationContext method and passes in itself as an argument to the setApplicationContext method. The Spring container requires the programmer to specify (inject) the BeanFactory parameter before calling setBeanDactory.
- If the Bean implementation BeanPostProcess interface, the Spring will invoke them postProcessBeforeInitialization initialization (pre) method (role is to be enhanced after the Bean instance to create successful treatment, such as to modify the Bean, add a function)
- If the beans implement the InitializingBean interface, Spring calls their afterPropertiesSet method in the same way that the Bean was initialized with the init-method declaration in the configuration file. Are initialization methods that are executed after all properties of the Bean have been set successfully.
- If the Bean implementation BeanPostProcess interface, the Spring will invoke them postProcessAfterInitialization initialization after () method (with 6, 6 is just before execution of the Bean is initialized, This is executed after the Bean is initialized, at a different time.)
- After the above work, the Bean will reside in the application context for use by the application until the application context is destroyed 10. If the Bean implements the DispostbleBean interface, Spring calls its destory method, which is executed before the Bean instance is destroyed, in the same way that the destory-method property is used on the Bean in the configuration file.
The listener
- implementation
javax.servlet.ServletRequestListener
.javax.servlet.http.HttpSessionListener, javax.servlet.ServletContextListener
Interface, etc. - It is used to monitor the creation and destruction of objects, such as session creation and destruction, request creation and destruction, and ServletContext creation and destruction
@Slf4j
@Component
@Conditional(JeecgCloudCondition.class)
public class SystemInitListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {
@Autowired
private ISysGatewayRouteService sysGatewayRouteService;
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
log.info("Service started, initial route configuration ###################");
if (applicationReadyEvent.getApplicationContext().getDisplayName().indexOf("AnnotationConfigServletWebServerApplicationContext") > -1) { sysGatewayRouteService.addRoute2Redis(CacheConstant.GATEWAY_ROUTES); }}@Override
public int getOrder(a) {
return 1; }}Copy the code
Spring listener —ApplicationListener
With active trigger listener
The filterFilter
Callback based implementation, belongs to the Web layer and relies on servlets
Applies to: Static resource requests
// You don't need any @enablexxx, just a Servlet in the framework
// Implements Filter
// Override methods init, doFilter, destroy
// Step 2: Inject filters into the Spring container in two ways
//1. Use annotations directly on custom filters
@Order
@WebFilter // Functions similar to FilterRegistrationBean register filter
@WebInitParam
//2. Inject the filter code into the registered Bean
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter(a) {
FilterRegistrationBean registration = new FilterRegistrationBean(); // belongs to a method in the Servlet used to register filters
registration.setFilter(new CostTimeFilter());
registration.addUrlPatterns("/ *");
registration.setName("CostTimeFilter");
registration.setOrder(1);
returnregistration; }}Copy the code
SpringBoot filters and how to use them
The interceptor
Based on reflection and AOP ideas, interception controller relies on the Spring framework for: unified permission control, dynamic requests
// Start @enableWebMVC. Spring Boot is enabled by default
/ / the first step: custom interceptors, extends HandlerInterceptor/HandlerInterceptorAdapter
// Override methods preHandle, postHandle, afterCompletion
// Step 2: Implements WebMvcConfigurer
Copy the code
Aspet
—AOP
Intercepting Services In practice, AOP is often combined with transactions
AOP
The implementation principle —- is reflection
Service Locator < == ==> Delegate < == ==> Reflection, dynamic proxy < == ==> Class methods are not called by their own instances, but delegated to the user to call autonomously
Spring uses the cglib library’s reflection implementation by default, not the JDK’s built-in reflection
The controllerThe servlet controller,
The parser... implements HandlerMethodArgumentResolver
Method parameter parser: the ViewResolver language parser is suitable for runtime modification of controller method parameters using annotations
// Start @enableWebMVC. Spring Boot is enabled by default
/ / the first step: custom parser, implements HandlerMethodArgumentResolver /... extends AbstractNamedValueMethodArgumentResolver
// Override methods createNamedValueInfo, resolveName, supportsParameter, handleMissingValue
// Step 2: Implements WebMvcConfigurer
Copy the code
Spring custom parameter parser reference code
Spring initiates a request process
ApplicationListener or custom event listener for container startup/destruction events -> front-end controller (DispatcherServlet) -> request to HandlerMapping -> Filter -> Servlet container (Tomcat) – Interceptor – Resolver – AOP – Controller – Validator – Command The Object to which the request parameters are bound is called a command Object) -> Form Object Is the value that needs to be returned to the front end.
Spring filters and interceptors – code implementation filters, interceptors, filter differences – depends on the Spring life cycle
The Spring framework
Spring project template recommendation
Spring MVC in detail
Spring Boot common components
Monitoring module
Spring Boot Actuator
与 Micrometer
Spring MVC
Model (Model
)
- Spring MVC passes model data to the view method summary
Request parameter verification
use
- Used in parameters in controller
@Validated
- in
entity
Use in files@valid
Annotate to mark for verificationElements of a set 和 Custom data types - Custom verifier, unified error message return format
Verification Details
Springboot group verification and custom parameter verification
Scattered knowledge points in Spring
Path matching
Classpath: classpath: : classpath: : classpath: : classpath: :org/jeecg/modules/**/ XML/mapper.xml: Classpath *:/mapper/**/*.xml: static resources in the output directory
Beans in Spring are singleton by default. Why can they be requested concurrently
Singleton member variables must be thread-safe. With ThreadLocal, singleton methods and their local variables are created in their own stack context each time they are called, so concurrency is guaranteed.
So there are two cases for member variables of all registered classes in Spring:
- Member variables are used
@Autowired
And the member method in the class definition of the member variable also satisfies condition 1 and condition 2 - Member variables are other common types, such as
Int, List, Set, Map
, the thread safety must be manually ensuredThreadLocal
.
The Spring Boot Web layer is based on servlets, where each request is a thread. In addition, database connections need to be thread isolated, because temporary tables, bound variables, and so on are only valid for the current session, and different sessions are isolated from each other. When there is a requirement to operate the database more than once in a single request, the multiple operations must be encapsulated in a transaction.
If Mybatis requests the database multiple times in the same method, do you want to create multiple SqlSession sessions? – Jane books (jianshu.com)
How does spring implement thread isolation in mybatis sqlSession? – When you get back. – Cnblogs.com