In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the knowledge points of Spring? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
1. The role of the Spring framework
Lightweight: Spring is lightweight and the basic version size is 2MB
Control inversion: Spring achieves loose coupling through control inversion, and objects give their dependencies instead of creating or finding dependent objects.
Aspect-oriented programming AOP:Spring supports aspect-oriented programming and separates application business logic from system services.
Container: Spring contains and manages the lifecycle and configuration of objects in the application
MVC framework: Spring-MVC
Transaction management: Spring provides a continuous transaction management interface that can be extended from local transactions down to global transaction JTA
Exception handling: Spring provides convenient API to integrate specific technology-related exceptions
2. Composition of Spring
Spring consists of seven modules:
Spring Core: the core container provides the basic functionality of the Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the inversion of Control (IOC) mode to separate the application's configuration and dependency specifications from the actual application code.
Spring context: the Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, email, internationalization, checksum and scheduling capabilities.
Spring AOP: through the configuration management feature, the Spring AOP module integrates aspect-oriented programming capabilities directly into the Spring framework. Therefore, you can easily make any object managed by the Spring framework support AOP. The Spring AOP module provides transaction management services for objects in Spring-based applications. By using Spring AOP, you can integrate declarative transaction management into your application without relying on EJB components.
The Spring DAO:JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exceptions follow the general DAO exception hierarchy.
The Spring ORM:Spring framework inserts several ORM frameworks, providing object-relational tools for ORM, including JDO, Hibernate, and iBatis SQL Map. All of this follows Spring's generic transaction and DAO exception hierarchy.
Spring Web module: the Web context module is built on top of the application context module, providing context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the work of handling multipart requests and binding request parameters to domain objects.
Spring MVC framework: the MVC framework is a full-featured MVC implementation for building Web applications. Through the policy interface, the MVC framework becomes highly configurable, and MVC hosts a number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
3. Spring container
Sping containers can be divided into two types
1. BeanFactory: (org.springframework.beans.factory.BeanFactory API definition) is the simplest container that provides basic DI support. The most commonly used BeanFactory implementation is the XmlBeanFactory class, which loads beans as defined in the XML file, and the container reads configuration metadata from the XML file and uses it to create a fully configured system or application.
2. ApplicationContext application context: (org.springframework.context.ApplicationContext) builds on top of BeanFactory and provides application-oriented services.
4. The usual implementation of ApplicationContext
ClassPathXmlApplicationContext: loads the context definition from the XML configuration file under the classpath and treats the application context definition file as a class resource.
FileSystemXmlApplicationContext: reads the XML configuration file under the file system and loads the context definition.
XmlWebApplicationContext: read the XML configuration file under the Web application and load the context definition.
ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml")
5. IOC & DI
Inversion of Control is generally divided into two types: dependency injection DI (Dependency Injection) and dependency lookup (Dependency Lookup). Dependency injection is widely used.
Spring IOC helps create objects, manage objects (DI), assemble objects, configure objects, and manage the entire lifecycle of those objects.
Advantages: reduce the amount of code applied to *. Container testing, with minimum cost and minimum intrusiveness, enables loose coupling. The IOC container supports hungry initialization and lazy loading when loading services.
DI dependency injection is an aspect of IOC and is a common concept with many interpretations. This concept means that you don't need to use a bedstead object, but only need to describe how it is created. You don't assemble your components and services directly in the code, but describe which services the components need in the configuration file, and then an IOC container helps assemble them.
The injection mode of IOC: 1. Constructor dependency injection; 2. Setter method injection.
6. How to provide configuration metadata to a spring container
XML profile
Annotation-based configuration
Java-based configuration @ Configuration, @ Bean
7. Attributes in the bean tag:
Id
Name
Class
Methods that will be called immediately after init-method:Bean instantiation
Methods that will be called before destory-method:Bean is removed and destroyed from the container
Factory-method: run we call a specified static method instead of the constructor to create an instance of a class.
The scope of scope:Bean, including singleton (default), prototype (create an instance for each call), request,session, global-session (note that the singleton bean in spring is not thread safe)
Autowired: auto-assembly byName, byType, constructor, autodetect (first explain using constructor auto-assembly, if no Bean matching the constructor is found, Spring will try to use byType auto-assembly)
8. Related attributes in the beans tag
Default-init-method
Default-destory-method
Default-autowire: the default is none, which applies to all Bean in the Spring configuration file. Note that this does not refer to the Spring application context, because you can define multiple profiles.
9. The life cycle of Bean
1) create an instance of Bean (factory-method, autowireConstrutor)
2) attribute injection (autowireByName, autowireByType)
3) initialize Bean
Activate Aware method: (invokeAwaresMethods) Spring provides some Aware-related APIs, such as BeanNameAware, BeanFactoryAware, ApplicationContextAware, etc. The bean that implements these Aware interfaces can obtain some corresponding resources after initialization.
Private void invokeAwareMethods (final String beanName, final Object bean) {
If (bean instanceof Aware)
{
If (bean instanceof BeanNameAware) {
((BeanNameAware) bean) .setBeanName (beanName)
}
If (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean) .setBeanClassLoader (getBeanClassLoader ())
}
If (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean) .setBeanFactory (AbstactAutowire CapableBeanFactory.this)
}
}
}
Application of the processor (BeanPostProcessor interface): the postProcessBeforeInitialization and postProcessAfterInitialization methods of BeanPostProcessor are called before and after the custom initialization method is called, so that users can respond according to their own business needs. 3.3.Activation of custom init methods (init-method & custom implementation of InitializingBean interface)
Protected Object initializeBean (final String beanName, final Object bean, RootBeanDefinetion mbd) {
If (System.getSecurityManager ()! = null) {
AccessController.doPrivileged (new PrivilegedAction () {
@ Override
Public Object run ()
{
InvokeAwareMethods (beanName,bean)
Return null
}
});
}
Else {
/ / A pair of special bean processing: Aware, BeanClassLoaderAware, BeanFactoryAware
InvokeAwareMethods (beanName,bean)
}
Object wrappedBean = bean
If (mbd = = null!! mbd.isSynthetic ()) {
WrappedBean = applyBeanPostProcessorsBeforeInitialization (wappedBean,beanName)
}
Try {
InvokeInitMethods (beanName, wappedBean, mbd)
}
Catch (Throwable ex) {
Throw new BeanCreationException ((mbd! = null? Mbd.getResourceDescription (): null), beanName, "Invocation of init method failed", ex)
}
If (mbd = = null | |! mbd.isSynthetic ()) {
WrappedBean = applyBeanPostProcessorsAfterInitialization (wrappedBean, beanName)
}
Return wappedBean
}
4) use Bean. Resides in the context of the application until the application context is destroyed. 5) destroy (destory-mthod & implement DisposableBean interface)
Or represent like this:
1. The construction of Bean
two。 Call the setXXX () method to set the properties of Bean
3. Call setBeanName () of BeanNameAware
4. Call the setBeanFactory () method of BeanFactoryAware
5. Call the postProcessBeforeInitialization () method of BeanPostProcessor
6. Call the afterPropertiesSet () method of InitializingBean
7. Call the custom initialization method
8. Call the postProcessAfterInitialization () method of the BeanPostProcessor class
9. Call the destroy () method of DisposableBean
10. Call the custom destroy method
10. Injecting collections into Spring
The allowable value is the same
The same value is not allowed
Keys and values can be of any type, and key, key-ref, value-ref and value can be matched arbitrarily.
XXX key and value can only be of type String
11. Assembly null value
twelve。 Automatic assembly (autowiring)
It helps to reduce or even eliminate configurations and elements, allowing Spring to automatically recognize how to assemble Bean dependencies. Correspondingly, automatic detection (autodiscovery) is a step closer than automatic assembly, allowing Spring to automatically identify which classes need to be configured as SpringBean, thereby reducing the use of elements.
13. Notes
Annotation assembly is disabled by default for Spring containers. The easiest way to open it. Several different annotations for automatic assembly supported by Spring:
@ Autowired annotations included with Spring
@ Inject comment on JSR-330
@ Resource comment on JSR-250
14. @ Autowired
@ Autowired has a strong contract feature, and its annotated attributes or parameters must be assemblable. If there is no Bean to assemble to the properties or parameters marked by @ Autowired, the autoassembly will fail, throwing a NoSuchBeanDefinitionException. Properties do not have to be assembled, and null values are acceptable. In this scenario, you can configure automatic assembly by setting the required property of @ Autowired to false, such as:
@ Autowired (required=false)
Private Object obj
Note that the required attribute can be used anywhere the @ Autowired annotation is used. But when assembling with a constructor, only one constructor can set the required property of @ Autowired to true. Other constructors annotated with the @ Autowired annotation can only set the required property to false. In addition, when multiple constructors are annotated with @ Autowired, Spring selects the constructor with the most input parameters from all the constructors that meet the assembly criteria. You can use @ Qualifier to explicitly specify the Bean to be assembled. As follows:
@ Autowired
@ Qualifier ("objName")
Private Object obj
15. Custom qualifier
@ Target ({ElementType.FIELF, ElementType.PARAMETER, ElementType.TYPE})
@ Retention (RetentionPolicy.RUNTIME)
@ Qualifier
Public @ Interface SpecialQualifier {}
At this point, you can use the custom @ SpecialQualifier annotation instead of @ Qualifier to label, or you can use it with @ Autowired:
@ Autowired
@ SpecialQualifier
Private Object obj
At this point, Spring narrows the scope of autoassembly to the Bean annotated by @ SpecialQualifier. If there are multiple Bean annotated by @ SpecialQualifier, we can further narrow it down by customizing another qualifier @ SpecialQualifier2.
16. @ Autowired pros and cons
Spring's @ Autowired annotation is one way to reduce Spring XML configuration. But its class reflects a specific dependency on Spring (even if the dependency is just an annotation).
17. @ Inject
Like the @ Autowired annotation, @ Inject can be used to automatically assemble properties, methods, and constructors; unlike @ Autowired, @ Inject has no required attribute. Therefore, the dependency annotated by the @ Inject annotation must exist, and if not, an exception will be thrown.
18. @ Named
The Qualifier,@Inject corresponding to @ Autowired corresponds to the @ Named annotation.
@ Inject
@ Named ("objName")
Private Object obj
19. SpEL expression
Grammatical forms use expressions in # {}, such as:
20. @ Value
@ Value is a new assembly annotation that allows us to use annotations to assemble values of type String and values of basic types, such as int, boolean. We can directly label a property, method, or method parameter through @ Value, and pass in an expression of type String to assemble the property, such as:
@ Value ("Eruption")
Private String song
@ Value can be used with SpEL expressions, for example, in some cases you need to read the contents of a properties file, you can use:
@ Value ("# {configProperties ['ora_driver']}")
For more information, please refer to Spring+Mybatis Multi-data Source configuration (3)-- how does Spring get information about Properties files?
21. Automatic detection of Bean
Element not only does the same work as, but also allows Spring to automatically detect Bean and define Bean. Element scans the specified package and all its child packages, as follows:
twenty-two。 Label Bean for automatic detection
By default, find classes annotated with stereotype annotations, these special annotations are as follows:
-@ Component: a generic stereotype annotation that marks this class as a Spring component
-@ Controller: identifies that the class is defined as SpringMVC controller
-@ Repository: identifies the definition of this class as a data warehouse
-@ Service: identifies that the class is defined as a service
Take @ Component as an example:
@ Component
Public class Guitar implements Intrument {}
Here @ Component will automatically register Guitar as Spring Bean, and set the default Id of Bean to guitar, and the first letter uppercase to lowercase. Note that if both the * * and the second letter are capitalized, the default Bean id will have special handling. You can also specify the Id of Bean, such as:
@ Component ("guitarOne")
Public class Guitar implements Intrument {}
23. AOP
Aspect-oriented programming AOP is a programming technique that allows programs to modularize horizontal cutting of concerns, or crosscutting typical divisions of responsibility, such as logging and transaction management.
The core of AOP is aspect, which encapsulates the common behavior of multiple classes into a reusable module that contains a set of API to provide crosscutting functions. For example, a log module can be called the AOP aspect of a log. Depending on the requirements, an application can have several aspects. In SpringAOP, aspects are implemented through classes with @ Aspect annotations.
The concern is the behavior of a module in the application, and a concern may be defined as a function that we want to implement.
Crosscutting concern is a concern that is used by the entire application and affects the entire application, such as logging, security, and data transfer, required by almost every module of the application. So these are crosscutting concerns.
The join point represents a location in an application where we can insert an AOP aspect, which is actually the location where the application executes Spring AOP.
A pointcut is a connection point or group of join points where notifications will be performed. The pointcut can be indicated by expression or by matching.
Introduce and run us to add new methods and properties to existing classes.
24. AOP Notification
Notification is an action to be done before and after the execution of a method, which is actually the code to be triggered by the SpringAOP framework when the program is executed
Five types of notifications can be applied to the Spring section:
Before: pre-notification, called before a method is executed. @ Before
After: a notification that is called after a method executes, regardless of whether the method execution was successful or not. @ After
After-returning: notification that is executed only when the method completes successfully. @ AfterReturning
After-throwing: the notification that is executed when the method throws an exception to exit. @ AfterThrowing
Around: notifications called before and after method execution. @ Around
25. Transaction type of Spring
Programmatic transaction management: this means that you manage transactions programmatically, giving you great flexibility but difficult to maintain. Declarative transaction management: this means that you can separate business code from transaction management, and you only need to use annotations and XML configuration to manage transactions.
twenty-six。 ACID
Atomic atomicity: a transaction is a unit of work consisting of one or more activities. Atomicity ensures that all operations in a transaction occur or do not occur.
Consistent consistency: once the transaction is completed, the system must ensure that the business it models is in a consistent state
Isolated isolation line: transactions allow data from multiple user object headers to be manipulated, and each user's operations are not entangled with other users.
Durable persistence: once the transaction is completed, the result of the transaction should be persisted so that it can recover from any system crash.
twenty-seven。 JDBC transaction
If you use JDBC directly for persistence in your application, for example, the blogger uses Mybatis,DataSourceTransactionManager to handle transaction boundaries for you. For example:
twenty-eight。 JTA transaction
If your transaction needs to span multiple transaction resources (for example, two or more databases, or if Sping+ActiveMQ integration requires the integration of ActiveMQ and database transactions), you need to use JtaTransactionManager:
JtaTransactionManager delegates the responsibility of transaction management to an implementation of JTA. JTA specifies a standard API for coordinating transactions between an application and one or more data sources. The transactionManagerName attribute indicates the JTA transaction manager to look for on the JNDI. JtaTransactionManager delegates responsibility for transaction management to javax.transaction.UserTransaction and javax.transaction.TransactionManager objects. Commit the transaction through the UserTransaction.commit () method. Similarly, if the transaction fails, the rollback () method of UserTransaction will be called.
twenty-nine。 Declarative transaction
Although Spring provides a variety of mechanisms for declarative transactions, all of them rely on these five parameters to control how transaction strategies are managed. Therefore, if you want to declare a transaction strategy in Spring, you need to understand these parameters. (@ Transactional)
1. Propagation behavior (propagation)
ISOLATION_DEFAULT: use the isolation level preset by the underlying database
ISOLATION_READ_COMMITTED: allows transactions to read data fields that have been sent (Commit) by other parallel transactions, preventing Dirty read problems
ISOLATION_READ_UNCOMMITTED: allows transactions to read data that has not been sent by other parallel transactions, resulting in problems such as Dirty, Nonrepeatable, Phantom read, etc.
ISOLATION_REPEATABLE_READ: requires that the data read multiple times must be the same, unless the transaction itself updates the data, which can prevent Dirty and Nonrepeatable read problems.
ISOLATION_SERIALIZABLE: a complete isolation level that prevents problems such as Dirty, Nonrepeatable, Phantom read, etc., and locks the corresponding data table, resulting in efficiency issues
two。 Isolation level (isolation)
PROPAGATION_REQUIRED- supports the current transaction, and if there is no transaction, create a new transaction. This is the most common choice.
PROPAGATION_SUPPORTS- supports the current transaction, and if there is no transaction, it is executed in a non-transactional manner.
PROPAGATION_MANDATORY- supports the current transaction and throws an exception if there is no current transaction.
PROPAGATION_REQUIRES_NEW- creates a new transaction and suspends the current transaction if it exists.
PROPAGATION_NOT_SUPPORTED- performs operations in a non-transactional manner, suspending the current transaction if there is a current transaction.
The PROPAGATION_NEVER- executes in a non-transactional manner and throws an exception if a transaction currently exists.
PROPAGATION_NESTED- if a transaction currently exists, it is executed within a nested transaction. If there is no transaction currently, do something similar to PROPAGATION_REQUIRED.
3. Read-only (read-only)
If the transaction only performs read actions, you can take advantage of some of the read-only actions that occur in the underlying database. Because this action takes advantage of the read-only transaction operations of the database, it must be valid in the transaction, that is, it must be set with the propagation behaviors PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW and PROPAGATION_NESTED.
4. Transaction timeout (timeout)
Some transaction operations may last for a long time, and the transaction itself may be related to the locking of the data table, so long-term transaction operations will have efficiency problems. For long transaction operations, consider Roll back transactions and require re-operation, instead of waiting for the transaction to be completed. You can set the transaction timeout period from the beginning of the transaction, so this setting must be set with the propagation behaviors PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW, and PROPAGATION_NESTED.
5. Rollback rules (rollback-for, no-rollback-for): rollback-for means that transactions should be rolled back and not committed for those checked exceptions; no-rollback-for means that transactions should continue to run for those exceptions without rollback. By default, Spring declares that the transaction rolls back all runtime exceptions.
thirty。 SpringMVC
The specific process of the core architecture:
First of all, the user sends the request-- > DispatcherServlet. After receiving the request, the front-end controller does not process it by itself, but entrusts it to other parsers to handle it as a unified access point for global flow control.
DispatcherServlet-- > HandlerMapping, HandlerMapping will map the request to a HandlerExecutionChain object (including a Handler processor (page controller) object and multiple HandlerInterceptor interceptors). Through this policy mode, it is easy to add new mapping policies.
DispatcherServlet-- > HandlerAdapter,HandlerAdapter will package processors as adapters to support multiple types of processors, that is, the application of adapter design patterns, making it easy to support many types of processors
HandlerAdapter-- > the call of the processor function processing method, HandlerAdapter will call the real processor function processing method according to the adaptation result, complete the function processing, and return a ModelAndView object (including model data, logical view name)
The logical view name of ModelAndView-- > ViewResolver. ViewResolver will parse the logical view name into a specific View. Through this policy mode, it is easy to change other view technologies.
View-- > render. View will render based on the incoming Model model data. The Model here is actually a Map data structure, so it is easy to support other view technologies.
Control is returned to DispatcherServlet, and DispatcherServlet returns the response to the user, at the end of this process.
thirty-one。 DispatcherServlet
At the core of SpringMVC is DispatcherServlet, which acts as the front-end controller for SpringMVC. Like other Servlet, DispatcherServlet must be configured in the web.xml file of the Web application.
Viewspace
Org.springframework.web.servlet.DispatcherServlet
two
By default, DispatcherServlet loads the Spring application context from a XML file based on this Servlet name when it loads. Because the name of servlet is viewspace, the name of the configuration file is viewspace-servlet.xml. Next, you must declare that DispatcherServlet handles those URL:
Viewspace
/
By mapping DispatcherServlet to /, it is declared that it will be the default servlet and will handle all requests, including requests for static resources. You can configure:
Deal with static resources.
thirty-two。 Configure HandlerMapping
Spring comes with several processor mapping implementations:
BeanNameUrlHandlerMapping: map the controller to URL based on the name of the controller Bean.
ControllerBeanNameHandlerMapping: similar to BeanNameUrlHandlerMapping, the controller is mapped to URL based on the name of the controller Bean. With this processor mapping implementation, the name of Bean does not need to follow the convention of URL.
ControllerClassNameHandlerMapping: map the controller to URL by using the controller's class name as the URL basis.
DefaultAnnotationHandlerMapping: map requests to controllers and controller methods annotated with @ RequestingMapping.
SimpleUrlHandlerMapping: map controllers to URL using familiar collections defined in the Spring application context.
Using these processor mappings as above is usually only necessary to configure a Bean in Spring. If the processor map Bean,DisapatchServlet is not found, BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping will be created and used. We generally use annotation-based controller classes.
When building the controller, we also need to use annotations to bind the request parameters to the controller's method parameters for verification and information conversion. Provides annotation-driven features.
thirty-three。 Configure HandlerAdapter
thirty-four。 Configuration View
In SpringMVC, the old age uses the development mode that convention is better than configuration. InternalResourceViewResolver is a convention-oriented element. It resolves the logical view name to a View object that delegates the task of rendering to a template in the context of the Web application.
When DispatcherServlet asks InternalResourceViewResolver to parse the view, it takes a logical view name, adding the "/ WEB-INF/jsp/" prefix and the ".jsp" suffix. The result of waiting is the JSP path of the rendered output. Internally, InternalResourceViewResolver then passes this path to the View object, which passes the request to the JSP. View object.
After reading the above, do you have any ways to master the knowledge of Spring? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.