1. The characteristics of the Spring

Spring has the following features:

  1. Lightweight: Spring is non-intrusive, where objects do not depend on Spring-specific classes;
  2. Inversion of Control (IoC) : With IoC, low coupling is promoted. Objects that an object depends on are passed in passively instead of being created or looked up by the object.
  3. Aspect oriented (AOP) : Support aspect oriented programming, separating application business logic layer and system service layer;
  4. Container: Contains and manages the configuration and lifecycle of application objects. Spring acts as a container.
  5. Set of frameworks: the ability to configure and combine simple components into more complex applications; In Spring, application objects are declaratively grouped in an XML file; In addition, Spring provides basic functions such as transaction management and persistence framework integration, leaving the development of application logic to the developer.

2. Spring core components

Spring is a layered architecture, mainly composed of the following seven modules. The Spring module resides in the core container and defines how beans are created, configured, and managed.

  1. Spring Core: Provides the basic functionality of the Spring framework. The main component is the BeanFactory, an implementation of the factory pattern that separates the application’s configuration and dependency specifications from the actual application code through the IOC mechanism.
  2. Spring Context: A configuration file that provides Context information to the Spring framework, including enterprise services such as JNDI, EJB, E-mail, internationalization, validation, and scheduling.
  3. Spring AOP: Spring AOP directly integrates AOP (aspect oriented) functionality into the Spring framework through configuration management features. This makes it very convenient to use the Spring framework to manage any OBJECT that supports AOP. The module provides transaction management services for objects in Spring-based applications. By using this component, you can integrate declarative transaction management into your application without relying on other components.
  4. Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error information thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written. Spring DAO’s JDBC-oriented exceptions follow the common DAO exception hierarchy.
  5. Spring ORM: Several ORM frameworks are inserted into the Spring framework to provide ORM object-relational tools, including JDO, Hibernate, and iBatis SQL Map, which comply with Spring’s common transaction and DAO exception hierarchy.
  6. Spring Web: The Web context module is built on top of the application context module to provide context for Web-based applications, so the Spring framework supports integration with Jakarta Structs. It also simplifies processing multi-part requests and binding request parameters to domain objects.
  7. Spring MVC: MVC is a full-featured MVC implementation for building Web applications that can be highly configurable with a policy interface to the MVC framework. MVC also accommodates view technologies such as JSP, Velocity, Tiles, etc.

3. Frequently used Spring annotations

annotations instructions
@Controller 1. Used to annotate control layer components

2. Mark a class to indicate that it is a SpringMVC Controller object

3. The distribution handler will scan the methods of classes that use the annotation and check whether the methods are used@RequestMapping

4. To be able toRequestrequestheaderPartial values are bound to method parameters
@RestController The equivalent of@Component@ResponseBodyThe combination of
@Component Generally refers to components, annotating when components are difficult to categorize
@Repository Used to annotateDAOLayer,DaoImplClass notes
@Service Used to annotate business layer components
@ResponseBody 1. Asynchronous request

2. Used toControllerMethod of the object returned by the appropriateHttpMessageConverterConvert to the specified format and write toResponseThe object’sbodyData area

3. The data returned is nothtmlPage, but some other format of data (JSON, XML) used
@RequestMapping An annotation used to handle the mapping of a request address, used for a class or method, and used for a class to indicate that all methods in the class that respond to the request have that address as the parent path
@Autowired Class member variables, methods, and constructors are annotated to complete automatic assembly@AutowiredUse to eliminateThe get and setmethods
@PathVariable Used to map the template variables in the request URL to the parameters of the functional processing method, that is, to take variables in the URL template as parameters
@RequestParam Used to get parameters in the Spring MVC backend control layer, similarrequest.getParameter("name")
@RequestHeader willRequestrequestheaderPartial values are bound to method parameters
@ModelAttribute In theControllerThis annotation is executed before all methods are called and can be used in annotations and method parameters
@SessionAttributes Put the value insessionScope, write inClassThe above
@Valid Entity data validation, combined with Hibernate Validator
@CookieValue To obtaincookieThe values in the

4. The IoC principle

4.1 define

Spring uses a configuration file to describe the interdependencies between beans, using Java’s reflection capabilities to instantiate beans and establish Bean dependencies. Spring’s IoC container provides advanced services such as Bean instance caching, life cycle management, Bean instance proxy, event publishing, resource loading, etc.

To summarize: IOC is responsible for creating objects, managing objects (via dependency injection), consolidating objects, configuring objects, and managing object lifecycle;

4.2 Spring container high-level view

  1. Spring is read first at startupBeanConfiguration information and generate a copy in the Spring containerBeanConfiguring the registry;
  2. Based on what was generated in the previous stepBeanConfigure the registry to instantiateBeanAnd assemble itBeanBetween;
  3. Will be instantiatedBeanLoad into the Spring containerBeanIn the cache pool, for upper-layer applications to use;

4.3 Scope and Lifecycle of Spring Beans

4.3.1 scope

In Spring, the objects that make up the body of an application and are managed by the Spring IoC container are called beans. In short, beans are objects that are initialized, assembled, and managed by the IoC container.

There are several types of Bean scopes:

  1. Singleton = Singleton = Singleton

Scoped as Singleton, this pattern is unsafe under multithreading, indicating that only one instance of a shared Bean will exist in the IoC container, and that all requests to the Bean whose primary ID matches the Bean definition will return the same instance of the Bean. A Singleton is a Singleton model in which a Bean object is automatically created when the container is created, regardless of whether it is used or not, and the same object is retrieved each time.

  1. Prototype: Used each time you create it

The scope is Prototype, indicating that there are multiple instances of a Bean definition, and that a Bean in this scope causes a new Bean instance to be created every time the Bean is requested. Prototype is a Prototype type that is not instantiated when we create the container. Instead, we create an object when we get the Bean, and each time we get a different object.

  1. Request: Requests one instance at a time

The scope is Request, which means that in an HTTP Request, the container returns the same instance of the Bean. That is, each HTTP Request has its own Bean instance, created according to a Bean definition. Valid only in the context of the Web-based Spring ApplicationContext. When an HTTP request is processed, Bean instances in the scope are destroyed.

  1. Session

The container returns the same instance of the Bean in an HTTP Session and creates new instances for different Session requests. The Bean instance is valid only in the current Session. Valid only in the context of the Web-based Spring ApplicationContext. When an HTTP Session is deprecated, beans in that scope are also invalidated.

Scope class instructions
Singleton There is only one Bean instance in the Spring IoC container, as a singleton, which is the default in Spring
Prototype Each time the Bean is called from the container, a new instance is returned, that is, each callgetBean()Method, equivalent tonewA new object
Request Each HTTP request creates a new Bean, applicable only to the WebApplicationContext environment
Session Each HTTP Session shares a Bean, and different sessions use different beans. This applies only to WebApplicationContext

4.3.2 Life Cycle

  1. Spring instantiates beans;
  2. Spring injects values and Bean references into the corresponding properties of the Bean;
  3. If the Bean implements the BeanNameAware interface, Spring passes the Bean’s ID to the setBeanName() method.
  4. If the Bean implements the BeanFactoryAware interface, Spring will callsetBeanFactory()Method, passing in a reference to the application where the Bean resides;
  5. If the Bean implements the ApplicationContextAware interface, Spring will callsetApplicationContext()Method, passing in a reference to the application where the Bean resides;
  6. If the Bean implements the BeanPostProcessor interface, Spring will callpost-ProcessBeforeInitalization()Methods;
  7. If the Bean implementsInitializingBeanInterface, which Spring will callafter-PropertiesSet()Method, similarly, if the Bean usesinit-methodIf an initialization method is declared, that method is also called.
  8. If beans implement the BeanPostProcessor interface, Spring will call theirpost-ProcessAfterInitialization()Methods;
  9. At this point, the beans are ready to be used by the application, and they will reside in the application context until the application is destroyed;
  10. If the Bean implements the DisposableBean interface, Spring will call itsdestory()Interface method; Likewise, if the Bean usesdestroy-methodIf the destruction method is declared, it will also be called;

4.4 Four Methods of Spring dependency Injection

  1. Constructor injection
// With parameters, easy to use the constructor for injection
public CatDaoImpl(String name){
	this.name = name;
}
Copy the code
<bean id="CatDaoImpl" class="com.cunyu.CatDaoImpl">
	<constructor-arg value="name"></constructor-arg>
</bean>
Copy the code
  1. Setter method injection
public class Id {
    private int id;

    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id; }}Copy the code
<bean id="id" class="com.cunyu.Id ">
    <property name="id" value="1801333"></property>
</bean>
Copy the code
  1. Static factory injection

The so-called static factory is to call the static factory methods to get their desired objects, and for the sake of Spring management, we can not use the “class”. Static method () “to get the object, should be in the form of Spring injection;

// Static factory
public class DaoFactory {
    public static final FactoryDao getStaticFactoryDaoImpl(a){
        return newStaticFacotryDaoImpl(); }}public class SpringAction {
    // The object to be injected
    private FactoryDao staticFactoryDao;
    // Inject the set method of the object
    public void setStaticFactoryDao(FactoryDao staticFactoryDao) {
        this.staticFactoryDao = staticFactoryDao; }}Copy the code
<bean name="springAction" class="com.cunyu.SpringAction" >
    <! -- Inject objects with static factory methods -->
    <property name="staticFactoryDao" ref="staticFactoryDao"></property>
</bean>
<! Retrieve static methods from factory class -->
<bean name="staticFactoryDao" class="com.cunyu.DaoFactory" factory-method="getStaticFactoryDaoImpl"></bean>
Copy the code
  1. Instance factory

An instance factory means that the method to get an instance of an object is not static, so you need to first new the factory class and then call the normal instance method.

// Example factory
public class DaoFactory {
    public FactoryDao getFactoryDaoImpl(a){
        return newFactoryDaoImpl(); }}public class SpringAction {
    // Inject the object
    private FactoryDao factoryDao;
    public void setFactoryDao(FactoryDao factoryDao) {
        this.factoryDao = factoryDao; }}Copy the code
<bean name="springAction" class="com.cunyu.SpringAction">
    <! -- use the example factory method to inject the object, corresponding to the following configuration file -->
    <property name="factoryDao" ref="factoryDao"></property>
</bean>

<! -- Get an object from a factory class -->
<bean name="daoFactory" class="com.cunyu.DaoFactory"></bean>
<bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>
Copy the code

4.5 Spring automatic assembly

To realize automatic assembly, it is mainly realized from the following two perspectives:

  1. Component Scanning: Spring automatically discovers beans created in the application context.
  2. Autowiring: Spring automatically satisfies the dependencies between beans;

Spring assembly includes manual transfer and automatic assembly. Manual assembly is through XML assembly, construction method, setter method and other methods.

There are several types of autowire that enable the Spring container to perform dependency injection through autowire.

Assembly way instructions
no Automatic assembly is not performed by default. You can set it explicitlyrefProperty to perform assembly
byName The Spring container is found in the configuration file through parameter name autowiringBeanautowireProperty is set tobyNameAfter attempting to match, load and theBeanProperty with the same nameBean
byType The Spring container is found in the configuration file through parameter type autowiringBeanautowireProperty is set tobyTypeAfter attempting to match, load and theBeanProperties of the same typeBeanIf more than one is foundBeanIf the condition is met, an error is thrown
constructor Similar to thebyTypeIf there is no fixed constructor parameter type with a parameter, an exception is thrown
autodetect First try to useconstructorTo automatic assembly, if not working, usebyTypeway

4.6 Advantages and disadvantages of IoC

  1. Advantages: The decoupling between components improves the maintainability and flexibility of the program;
  2. Disadvantages: Complex steps to create the object, there is a certain learning cost; Using reflection to create objects is less efficient.

5. Principle of AOP

5.1 define

That is, to cut inside the encapsulated object and encapsulate the common behavior that affects multiple classes into a reusable module called an Aspect. The so-called aspect is not related to business, but the logic shared by business modules, which is convenient to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate subsequent operability and maintainability.

By using crosscutting, AOP splits software into core concerns and crosscutting concerns. The main processes of business processing are core concerns and have little to do with crosscutting concerns. The characteristic of crosscutting concerns is that they often occur in multiple places of the core concern and are generally similar everywhere. The role of AOP is to separate concerns in a system, separating core concerns from crosscutting concerns.

5.2 Core Concepts

5.3 Two proxy methods of AOP

Spring provides two ways to generate Proxy objects: JDK Proxy and CGlib. The default policy is to use JDK dynamic Proxy technology if the target class is an interface, or CGlib to generate the Proxy otherwise.

  1. JDK dynamic interface proxy

It mainly involves Proxy and InvocationHandler. InvocationHandler is an interface that defines crosscutting logic by implementing this interface and dynamically codifies crosscutting logic with business logic by invoking the code of the target class through reflection mechanism. Proxy uses InvocationHandler to dynamically create an instance conforming to an interface and generate Proxy objects of the target class.

  1. CGlib dynamic proxy

Code Generation Library is a high performance and high quality Code Generation Library that can extend Java classes and implement Java interfaces at run time. CGlib encapsulates ASM and dynamically generates new classes at run time.

  1. The difference between JDK dynamic proxy and CGlib dynamic proxy

The JDK dynamic proxy can only create proxy instances for interfaces. For classes that do not define business methods through interfaces, dynamic proxies need to be created through CGlib.

5.4 Section notification types

  1. Before: the notification is called Before the target method is called;
  2. After: the notification is called After the target method has completed;
  3. After-returning: Notification called After successful execution of the target method;
  4. After-throwing: calling notification After the target method has thrown an exception.
  5. Around: Performs custom behavior before and after the notified method call;

6. Spring MVC

6.1 What is the MVC Framework?

MVC, the full name Model View Controller, is the abbreviation of Model (Model) – View (View) – Controller (Controller), is a Model of software design. Organize the code in a separate way of business logic, data and interface display, gather the business logic into one component, and then improve and customize the interface and user interaction without rewriting the business logic;

MVC design pattern has the following benefits:

  1. Through hierarchical design, the structure among the components of the business system is realized, which is conducive to the scalability and maintainability of the business system.
  2. It is conducive to the parallel development of the system and improves the development efficiency.

6.2 for SpringMVC

6.2.1 definition

Spring MVC is a module of Spring framework, a framework based on MVC;

6.2.2 components

  1. DispatcherServlet: The core component, the front controller, also called the central controller, which schedules the related components,It’s used to receive requests and responses. It’s like a repeater. There you goDispatcherServletThis reduces the coupling between the other components;
  2. HandlerMapping: Processor mapper, which maps to different URL pathsHandler;
  3. HandlerAdapter: Processor adapter, according toHandlerAdapterRules to enforceHandler;
  4. Handler: Processor, developed by us according to the business;
  5. ViewResolver: View parser, which resolves logical views into concrete views;
  6. View: an interface that supports different view types

6.2.3 MVC workflow

  1. The browser sends the request, and the front end controls the areaDispatcherServletIntercept the request;
  2. DispatcherServletAfter intercepting the request, the request URL is parsed to obtain the request resource identifier URI, and the request is invoked according to the URIHandlerMappingObtain the correspondingHandler;
  3. DispatcherServletgetHandlerAfter that, I foundHandlerAdapter, through which to accessHandler, and execute the processor;
  4. performHandlerTo return aModelAndViewObject toDispatcherServlet;
  5. thenDispatcherServletrequestViewResolverParse the view, and parse the real view based on the logical view nameView;
  6. thenViewResolverWill be parsedViewBack to theDispatcherServletAnd then toViewRender;
  7. And then byDispatcherServletResponse view to the browser;

6.2.4 Advantages of SpringMVC

  1. Features of Spring;
  2. Support for multiple views;
  3. Easy configuration, non-invasive;
  4. Layer more clear, conducive to the team development of code maintenance, as well as good readability;

6.3 annotations

6.3.1 Principle of annotation

An Annotation is essentially a special interface that integrates annotations, and its implementation class is a dynamic proxy class generated by the Java runtime. When an annotation is retrieved through reflection, a dynamic proxy object generated by the Java runtime is returned. By the method of proxy objects call custom annotations will eventually call AnnotationInvocationHandler invoke method, and then the method from the Map of memberValues index out corresponding values;

6.3.2 Common Annotations

annotations instructions
@RequestMapping Used to process requestsurlA mapping annotation that can be used on a class or method to indicate that all methods responding to a request have this address as the parent path
@RequestBody Implement receivingHTTPThe request ofjsonThe data,jsonTo a Java object
@ResponseBody Implementation willcontrollerThe return object is converted into a Json object in response to the client