Just cut to the chase. Bring us the dry goods.

This article is reproduced. Original link:www.nowcoder.com/discuss/581…

1. Spring features

Spring has the following features:

(1) Lightweight: Spring is non-invasive, where objects do not depend on Spring’s specific classes.

(2) Inversion of control (IOC) : Through IOC, low coupling is promoted, and other objects dependent on one object are passed in passively, without the object being actively created or searched.

(3) Section-oriented (AOP) : support section-oriented programming, separating the application business logic layer and system service layer.

(4) Container: Contains and manages the configuration and life cycle of application objects, in which Spring acts as a container.

(5) Framework set: simple components can be configured and combined into more complex applications; In Spring, application objects are declaratively grouped in an XML file; At this point, Spring also provides transaction management, persistence framework integration and other basic functions, leaving the development of application logic to the developer.

2. Spring core components

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

(1) Spring Core: Provides the basic functions of the Spring framework. The main component is BeanFactory, which is the implementation of the factory mode. Through IOC mechanism, the configuration and dependency specifications of application programs are separated from the actual application code.

(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: Through configuration management features, Spring AOP directly integrates AOP (aspect oriented) functionality into the Spring framework. This makes it very easy to use the Spring framework to manage any AOP-enabled objects. The module provides transaction management services for objects in Spring-based applications. By using this component, jiujiang declarative transaction management can be integrated into the 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 jDBC-oriented exceptions follow a common DAO exception hierarchy.

(5) Spring ORM Several ORM frameworks have been inserted into the Spring framework to provide ORM object relationship tools, including JDO, Hibernate, and iBatis SQL Map, which comply with Spring’s common transaction and DAO exception hierarchies.

(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 handling 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 to the MVC framework through the policy interface. MVC also accommodates view technologies such as JSP, Velocity, and Tiles.

3. Common Spring annotations

4. IoC principle

4.1 define

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

To sum up: IOC is responsible for creating objects, managing objects (through dependency injection), integrating objects, configuring objects, and managing their life cycle;

4.2 Spring Container High-level View

(1) When Spring starts, read Bean configuration information first, and generate a corresponding Bean configuration registry in the Spring container;

(2) Instantiate beans according to the Bean configuration registry generated in the previous step, and assemble the dependencies between beans;

(3) Load the instantiated Bean into the Bean cache pool in the Spring container for use by upper-layer applications;

4.3 Scope and life cycle of Spring Beans

4.3.1 scope

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

Beans have the following scopes:

(1) Singleton

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

Prototype: used every time you create a Prototype

The scope is Prototype, indicating that a Bean definition corresponds to multiple instances, and that a Bean in this scope causes a new Bean instance to be created each 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.

(3) Request: Request one instance at a time

The scope is Request, indicating 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. This only works in web-based Spring ApplicationContext situations. When an HTTP request processing ends, the Bean instances in that scope are destroyed.

(4) the Session

The scope is Session, indicating that in one HTTP Session, the container returns the same instance of the Bean, and creates new instances for different Session requests. The Bean instance is valid only for the current Session. This only works in web-based Spring ApplicationContext situations. When an HTTP Session is discarded, beans in that scope are also invalidated.

4.3.2 Life cycle

(1) Spring instantiates the Bean;

(2) Spring injects values and Bean references into Bean properties;

(3) Spring passes the Bean ID to the setBeanName() method if the Bean implements the BeanNameAware interface;

(4) If the Bean implements the BeanFactoryAware interface, Spring calls the setBeanFactory() method to pass in the Bean’s application reference;

(5) If the Bean implements the ApplicationContextAware interface, Spring calls the setApplicationContext() method to pass in a reference to the Bean’s application;

(6) if the Bean implements the BeanPostProcessor interface, the Spring will call the post – ProcessBeforeInitalization () method;

(7) If the Bean implements the InitializingBean interface, Spring will call their after-propertiesSet () method. Similarly, if the Bean declares an initialization method using init-method, this method will also be called;

(8) if the Bean implements the BeanPostProcessor interface, the Spring will call them in the post – ProcessAfterInitialization () method;

(9) At this point, the Bean is ready for use 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 its deStory () interface method; Similarly, if the Bean declares a destroy method with destroy-method, that method will also be called;

4.4 Four methods of Spring dependency Injection

(1) Constructor injection

// add parameters to facilitate injection with the constructor
public CatDaoImpl(String name){
    this.name = name;
}
Copy the code

(2) 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

(3) Static factory injection

A static factory is a method that calls a static factory to get the object you want, and for Spring management purposes, we can’t use a “class”. Static method () “to get objects instead of spring-injected form;

// Static factory
public class DaoFactory {
    public static final FactoryDao getStaticFactoryDaoImpl(a){
        return newStaticFacotryDaoImpl(); }}public class SpringAction {
    // The object to inject
    private FactoryDao staticFactoryDao; 
    // Inject the set method of the object
    public void setStaticFactoryDao(FactoryDao staticFactoryDao) {
        this.staticFactoryDao = staticFactoryDao; }}Copy the code

(4) Example factory

Instance factory means that the method to get an instance of an object is not static, so you need to 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 objects
    private FactoryDao factoryDao; 
    public void setFactoryDao(FactoryDao factoryDao) {
        this.factoryDao = factoryDao; }}Copy the code

4.5 Spring automatic assembly mode

To achieve automatic assembly, mainly from the following two perspectives:

(1) Component Scanning: Spring automatically discovers beans created in the application context;

(2) Autowiring: Spring automatically satisfies dependencies between beans;

Spring assembly includes manual assembly and automatic assembly, with manual assembly through XML assembly, constructors, setter methods, and so on.

There are several types of autowiring, which enable the Spring container to implement dependency injection through autowiring.

4.6 Advantages and disadvantages of IoC

(1) Advantages: decoupling between components improves program maintainability and flexibility;

(2) Disadvantages: The steps of creating objects are complicated and there is a certain learning cost; Using reflection to create objects is less efficient;

5. AOP principles

5.1 define

That is, slice open the inside of the encapsulated object and encapsulate the common behavior that affects multiple classes into a reusable module named Aspect, or Aspect. The so-called section refers to the logic that has nothing to do with business, but is common to business modules. It is convenient to reduce the repetitive code of the system, reduce the coupling degree between modules, and facilitate the subsequent operability and maintainability.

Using crosscutting, AOP divides software into core concerns and crosscutting concerns. The main flow of business processing is the core concern and has little to do with crosscutting concerns. Crosscutting concerns are characterized by the fact that they often occur at multiple points of the core concern and are generally similar everywhere. AOP’s role is to separate the various concerns in a system, separating core concerns from crosscutting concerns.

5.2 Two proxy methods of AOP

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

(1) JDK dynamic interface proxy

It mainly involves Proxy and InvocationHandler, which is an interface that dynamically compacts crosscutting logic with business logic by implementing the interface that defines crosscutting logic and invokes the code of the target class through reflection. Proxy uses InvocationHandler to dynamically create an instance conforming to an interface and generate the Proxy object of the target class.

(2) CGlib dynamic proxy

Code Generation Library is a high performance and high quality Code Generation Library, which can extend Java classes and realize Java interfaces at run time. CGlib encapsulates ASM to dynamically generate new classes at run time.

(3) JDK dynamic proxy and CGlib dynamic proxy difference

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

5.3 Notification type of section

(1) Before notification: the target method invokes the notification Before it is called;

(2) Post-notification (After) : call notification After the target method completes;

(3) After-returning: call notification After successful execution of target method;

(4) After-throwing: call the notification After the target method throws an exception;

(5) Around notification: perform custom behavior before and after a notified method call;

In addition to the learning materials sorted out in this article, I also sorted out more detailed Java learning materials, a number of Internet companies and a number of tycoons’ interview materials, as well as more interview skills. Friends in need can click into access. Code word: nuggets. Good good study together, day day up!

6, Spring MVC

6.1 What is the MVC Framework?

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

Adopting the MVC design pattern has the following benefits:

(1) Through hierarchical design, the structure between 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 the Spring framework, an MVC based framework;

6.2.2 components

(1) DispatcherServlet: core component, front-end controller, also known as the central controller, by it to dispatch related components, used to receive requests, response results, equivalent to a forwarder, with DispatcherServlet to reduce the coupling degree between other components;

(2) HandlerMapping: a processor mapper that maps to different handlers according to the URL path;

(3) HandlerAdapter: processor adapter, according to the rules of the HandlerAdapter to execute the Handler;

(4) Handler: processor, which is developed by ourselves according to business;

(5) ViewResolver: ViewResolver, which resolves the logical view into a specific view;

(6) View: an interface that supports different View types;

6.2.3 MVC Workflow

(1) The browser sends a request, and the DispatcherServlet of the front-end control area intercepts the request;

(2) After intercepting the request, the DispatcherServlet parses the request URL to obtain the request resource identifier URI, and calls HandlerMapping according to the URI to obtain the corresponding Handler;

(3) After the DispatcherServlet gets to the Handler, it finds the HandlerAdapter through which to access the Handler and execute the processor;

(4) Execute Handler logic and return a ModelAndView object to DispatcherServlet;

(5) Then the DispatcherServlet requests the ViewResolver to parse the View and the real View according to the logical View name;

(6) Then the ViewResolver returns the parsed View to DispatcherServlet and renders the View;

(7) Then the DispatcherServlet responds to the view to the browser;

6.2.4 Advantages of SpringMVC

(1) With Spring features

(2) Support multiple views

(3) Convenient configuration, non-invasive

(4) The hierarchy is clearer, which is conducive to the maintenance of the code developed by the team, as well as good readability

6.3 annotations

6.3.1 Principles of Annotations

Annotations are essentially a special interface that integrates annotations, implemented by dynamic proxy classes generated by the Java runtime. When an annotation is retrieved by reflection, it returns a dynamic proxy object generated by the Java runtime. 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

7. Write at the end

This article has come to a full stop. There is always a thank-you at the end of an article. Similarly, if you are reading this article and find any errors in this article, or if you have anything to add, please correct them.

All right. If this article helps you, don’t forget to click three times. Thank you!