It will take about 7 minutes to read the full text

preface

Most articles say “what to Spring?” Inversion of control (IoC) or dependency injection (DI) and aspect oriented programming (AOP)**, take the official website document literal copy. For xiaobai is not friendly, after reading may still be confused. Here are some materials, books and my own understanding that I compiled in my spare time in an effort to talk about Spring in a more accessible way.

  • preface
  • What is Spring?
  • Spring modules
  • The advantages of the Spring
  • I understand Spring IoC and AOP
    • IoC (Inversion of Control)
    • AOP (aspect-oriented programming) is Aspect OrientedProgramming
  • The Spring bean
    • What are the scopes of beans?
    • Spring bean singletons and thread safety issues
    • The life cycle of Spring beans
    • Talk about your understanding of Spring MVC
  • Spring Transaction Declaration
    • The important point is this
  • Afterword.

What is Spring?

Spring is an open source framework. Spring is a lightweight Java development framework that started in 2003. Derived from some of the concepts and prototypes elaborated by Rod Johnson in his book Expert One-On-One J2EE Development and Design. It was created to address the complexity of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows consumers to choose which components to use while providing an integrated framework for J2EE application development. Spring uses basic Javabeans to do things that were previously only possible with EJBs.

However, Spring’s use is not limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. At Spring’s core are inversion of Control (IoC) and aspect oriented (AOP). Simply put, Spring is a layered JavaSE/EE full-stack lightweight open source framework.

In simple terms, it is a container framework for holding Javabeans (Java objects), and a mid-tier framework (universal glue) can serve as a link, such as gluing Struts and Hibernate together. In simple terms, Spring is a lightweight Inversion of Control (IoC) and AOP oriented container framework.

If you’re still a little confused, read through it and you’ll get something

Spring modules

The following content is based on Spring 4 and above

Spring official website image


  • Spring Core: Spring Core module, mainly provides ioC dependency injection,
  • Spring Context: Provides Context information to the Spring framework,
  • Spring AOP: Section-oriented programming that provides transaction management services for objects in Spring-based applications,
  • Spring JDBC: Java database connection,
  • Spring JMS: Java Messaging Service,
  • Spring ORM: used to support MyBatis, Hibernate and other ORM tools,
  • Spring Web: Provides support for creating Web applications,
  • Spring Test: Provides support for JUnit and TestNG tests,
  • Spring Aspects: This module provides support for integration with AspectJ.
  • Spring Web: The Spring framework supports integration with Struts, providing a context for Web-based applications.

The advantages of the Spring

  • Easy decoupling and easy development (high cohesion and low coupling) Spring is a large factory (container) that leaves all object creation and dependency maintenance to Spring, which is used to generate beans

  • AOP programming support Spring provides section-oriented programming, which can facilitate the implementation of procedures for permission interception, running monitoring and other functions

  • ** Support for declarative transactions ** Transactions can be managed through configuration without manual programming

  • Spring’s support for Junit4 makes it easy to test Spring programs with annotations

  • Spring is open source and provides direct support for Struts, Hibernate, MyBatis, Quartz, etc

  • Reducing the difficulty of using JavaEE apis Spring provides encapsulation for some apis that are very difficult to use in JavaEE development (JDBC, JavaMail, remote call, etc.), which greatly reduces the difficulty of using these apis

I understand Spring IoC and AOP

The most important concepts in Spring are IoC and AOP

IoC (Inversion of Control)

IoC needs DI(dependency injection) support why? Since Spring creates empty objects that are unusable without DI injection, IoC and DI are mostly seen at the same time.

IOC is an Inversion of Control, which most books translate as “Inversion of Control”. In order to solve the problem of over-coupling between objects, software expert Michael Mattson proposed IOC theory to achieve decoupling between objects **.

In 2004, Martin Fowler addressed the same question: since IOC is inversion of control, what is it that is reversed? After detailed analysis and argument, he came to the answer: “The process of obtaining dependent objects is reversed”. When control is reversed, the process of obtaining dependent objects is changed from self-management to active injection by the IOC container. He gave inversion of control a more appropriate name: Dependency Injection. His answer, in fact, suggests the way to achieve IOC: injection. Dependency injection is the dynamic injection of certain dependencies into objects by the IOC container at run time.

Dependency injection (DI) and inversion of control (IOC) are described from different perspectives as the same thing, which refers to the decoupling of objects by means of dependency injection through the introduction of the IOC container.

So with the background, let me give you my understanding

IoC is a design idea that relies on the inversion principle, that is, the control of manually created objects in the program is handed over to the Spring framework. The Spring framework is responsible for controlling the life cycle of objects and the relationships between them. IoC is also used in other languages, not unique to Spirng. Ioc container is actually a map (key, value), inside put is all sorts of objects (in the XML configuration bean node | | repository, service, controller, component).

The Spring IOC container is like a factory. When we need to create an object, we just need to configure the configuration file/annotations, regardless of how the object was created. The IOC container is responsible for creating objects, wiring them together, configuring them, and handling them throughout their life cycle from creation until they are completely destroyed.

In a real project, if a Service class has hundreds or even thousands of classes as its underlying class and we need to instantiate the Service, you might have to figure out the constructors of all the underlying classes of the Service every time, which can drive people crazy. With IOC, all you need to do is configure it and then reference it where you need it, which makes your project much more maintainable and easier to develop.

Recommended reading:

https://www.zhihu.com/question/23277575/answer/169698662

The IoC container initialization process can be divided into three steps:

  1. Resource location (Bean definition file location),
  2. Load the Resource with the Resource positioned into the BeanDefinition,
  3. Register BeanDefiniton with the container

The IoC source code:

https://javadoop.com/post/spring-ioc

AOP (aspect-oriented programming) is Aspect OrientedProgramming

What is AOP?

AOP (Aspect Oriented Programming for section Programming) is mainly used to solve some system level problems in program development, such as log collection, transaction management, permissions, cache, object pool management and so on.

AOP can be said to be OOP (Object Oriented Programming, object-oriented Programming) complement and perfect. OOP introduces concepts such as encapsulation, inheritance, and polymorphism to build a hierarchy of objects that simulate a collection of common behaviors. OOP, however, allows developers to define vertical relationships, but not horizontal ones, such as logging. Logging code tends to be spread horizontally across all object hierarchies, regardless of the core functionality of the object to which it corresponds. This is also true for other types of code, such as security, exception handling, and transparency persistence. This scattering of irrelevant code is called cross cutting. It leads to a lot of code duplication and is not conducive to reuse of modules.

AOP, on the other hand, uses a technique called “crosscutting” to rip open the insides of wrapped objects and encapsulate common behavior that affects multiple classes into a reusable module named “Aspect, “or Aspect. The so-called “facets”, simply speaking, are those unrelated to the business, but are encapsulated by the logic or responsibility of business modules, which is convenient to reduce the repetitive code of the system, reduce the degree of coupling between modules, and is conducive to the future operability and maintainability.

Spring AOP

Spring AOP is based on dynamic proxies. There are two underlying implementations: JDK Proxy and CGLib(Code Generation Library based on bytecode manipulation).

If the object to be propped is an implementation class, Spring uses JDK dynamic proxies (Spirng uses JDK dynamic proxies by default). If the proxied object is not an implementation class, Spring forces the use of CGLib to implement dynamic proxiing.


Recommended reading: https://www.jianshu.com/p/5b9a0d77f95f

Of course, you can also use AspectJ, which can do things Spring AOP can’t, and is a complete solution to AOP programming.

What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is runtime enhancement; AspectJ is compile-time enhancement. Spring AOP can only be woven at runtime; AspectJ runtime weaving is not available and supports compile-time, compile-time, and load-time weaving.

AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple.

The Spring bean

What are the scopes of beans?


Spring bean singletons and thread safety issues

Thread safety has always been an important area of code writing, and most of the time we don’t use multithreading in system development. Singleton beans are thread-safe. When multiple threads operate on the same object, the object’s non-static member variables are thread-safe.

Solutions:

  1. Define a ThreadLocal member variable in the class and store the required variable member variables in the ThreadLocal (one of the recommended methods, and one that is often used);

2. Try to avoid defining mutable member variables in Bean objects.

The life cycle of Spring beans

In traditional Java applications, the bean life cycle is simple: the bean is instantiated using the Java keyword new, and then the bean is ready for use. Once the bean is no longer in use, it is automatically garbage collected by Java.

In contrast, the life cycle of Spring’s managed beans is much more complex, and it is important to understand the life cycle of beans correctly. A Bean construction process:


Talk about your understanding of Spring MVC

Speaking of Spring, you must mention Spring MVC, and you have seen a lot of technical blogs about SSM.

When I first learned Java, I talked about the development mode of “Java Bean(Model) + JSP (View) + Servlet (Controller)”, which was the early JavaWeb MVC.

Spring MVC is an excellent MVC framework. It makes our development simpler, and it seamlessly integrates with Spring, is a sub-module of Spring, and is the Web module of the Spring family we mentioned above.

Spring MVC framework is mainly composed of DispatcherServlet, processor mapping, processor (controller), view parser and view.

The Spring MVC flowchart is important:


Spring Transaction Declaration

Transaction management is critical to enterprise applications to ensure data consistency even if exceptions occur.

  1. Programmatic transactions, hard-coded in code. (Not recommended)
  2. Declarative transactions, configured in configuration files (recommended)

Declarative transactions fall into two categories:

  1. Declarative TRANSACTIONS based on XML
  2. Annotation-based declarative transactions

The important point is this

Annotation @transactional (rollbackFor = exception.class

If you do not configure the rollbackFor attribute in the @Transactional annotation, then things will rollback only when RuntimeException is encountered, plus rollbackFor= exception.class , allowing things to roll back even if they encounter a non-runtime exception.

Afterword.

Scope means scope. In PUBG, scope means scope. If your teammate is a foreigner, you can say “I want this 4times scope” and he will understand.

The next chapter explains the code together