1 Spring core components

In a word: Spring is a lightweight, non-invasive inversion of Control (IoC) and AOP framework.

PS: The current standard configuration of Java development is Spring5 + Spring Boot 2 + JDK 8

1.1 introduction of Spring

Nowadays, Java development is also referred to as Spring development. Spring is the first major framework in Java. It makes the existing technology easier to use, promotes good programming habits, and greatly simplifies the development of applications.

Because if you think about it, if we want to implement a certain function, the amount of code is usually fixed, and we can either write it all by ourselves or use the existing excellent framework. Spring has provided us with various excellent components, but also provides a good code organization logic and business development process specification framework. Its main advantages are as follows:

  1. IOC and DI support

Spring is a large factory container that allows all object creation and dependency maintenance to be managed by Spring. The Spring factory is used to generate beans and manage their life cycle, implementing the design concept of high cohesion and low coupling.

  1. Support for AOP programming

Spring provides section-oriented programming, which can facilitate the implementation of programs for permission interception, running monitoring and other functions.

  1. Support for declarative transactions

Transactions can be managed through configuration without manual programming, and some of the JDBC operations that have been repeated before do not need to be written.

  1. Convenient program testing

Spring provides support for Junit4, making it easy to test Spring programs with annotations.

  1. Adhesive function

It is easy to integrate excellent frameworks. Spring does not exclude excellent open source frameworks and provides direct support for excellent frameworks such as Struts, Hibernate, MyBatis, Quartz, etc.

  1. Reduce the difficulty of using JavaEE apis

Spring provides a wrapper around some of the most difficult apis in JavaEE development (JDBC, JavaMail, remote calls, etc.), which makes it much easier to use.

1.2 Spring components

The Spring framework exists in modules. Except for Spring Core Container, which is the most essential module, all modules are optional. There are about 20 modules.

The Spring framework has many features, made up of seven well-defined modules.

Spring Core: The Spring Core, the most basic part of the framework, provides IOC and DI features.

Spring Context: The Spring Context container, which is a BeanFactory enhanced subinterface.

Spring Web: It provides support for Web application development.

Spring MVC: It is an implementation of the MVC idea in Web applications.

Spring DAO: Provides an abstraction layer for JDBC, simplifying JDBC coding and making coding more robust.

Spring ORM: It supports integration for popular ORM frameworks, such as Spring + Hibernate, Spring + iBatis, Spring + JDO integration, etc.

Spring AOP: Aspect oriented programming, which provides a programming implementation that is compatible with the AOP consortium.

2 the IOC and AOP

The two topics that Spring will never talk about are IOC and AOP. These are the two core topics of Spring. Beginners should not be intimidated by the terms IOC, AOP, Aspect, Pointcut, and Advisor, all of which are coined by boring people to write papers.

2.1 the IOC

Java is an object-oriented programming language. Generally, an application is composed of business logic developed by a group of objects cooperating with each other. How do you manage these objects? Abstract factory and factory method design patterns can help us create objects, and generator patterns can help us deal with the dependencies between objects, but these require us to create other factory and generator classes, and we have to manage these classes, adding to our burden. If the application can automatically manage the object’s declaration cycle when the object needs it, we don’t have to manage the Bean’s declaration cycle ourselves, which is decoupling.

Spring presents the idea that Spring is responsible for controlling the life cycle of objects and the relationships between them. All classes will be registered in the Spring container, telling Spring what the class is and what it needs, and Spring will voluntarily give you what you need when the system is running properly, as well as handing you over to other beans that need you. The creation and destruction of all classes is controlled by Spring, which means that it is not the reference object that controls the life cycle of an object, but Spring. For a specific object, it used to control other objects, but now all objects are controlled by Spring, so this is called Inversion of Controller, or Dependency Injection DI.

Given the general idea, if you try to implement IOC yourself, you’ll find that the core is reflection + XML parsing/annotation parsing.

Read XML to get bean information, class information, attribute value information.

Get the constructor of the target class through reflection, call the constructor, and assign a value to the object.

If you want to follow the source code you will find that the source entry of IOC is refresh(), which contains 13 functions to provide different functions, the specific process is more complex, public number reply IOC to obtain the original image.

2.2 the Context

The IOC container only provides space for managed objects. How do we put objects into the container that we need the container to manage for us? This involves the Spring application Context.

Application Context:

Based on Core and Beans, it provides a number of extensions, including internationalization operations (based on JDK), resource loading (based on JDK Properties), data validation (a data validation mechanism that Spring encapsulates itself), data binding (spring-specific, The parameters in the HTTP request are directly mapped as POJOs, type conversion, and the ApplicationContext interface is the core of Context, which can be understood as the Context or background information of the Bean.

It is easy to understand that the ApplicationContext is an abstract representation of the Spring container, and the common ApplicationContext is essentially a high-level interface that maintains Bean definitions and collaboration between objects. The Spring framework itself provides a number of container implementations, which fall into two categories:

  1. One is the less commonly used BeanFactory, which is the simplest container that provides only basic DI functionality.
  2. The other is the ApplicationContext derived from the BeanFactory. Its abstract interface is the ApplicationContext mentioned above, which can provide more enterprise-level services, such as parsing configuration text information, and so on. This is also the most common application scenario of ApplicationContext instance objects. With context objects, we can register objects with the container that need to be managed by Spring. For context abstraction interfaces, Spring also provides several types of container implementations that we can choose from in different application scenarios.

AnnotationConfigApplicationContext: from one or more configuration based on Java class loading context definition, apply to the way Java annotations.

ClassPathXmlApplicationContext: from the classpath of one or more XML configuration file loaded context definition, apply to the XML configuration.

FileSystemXmlApplicationContext: from the file system under one or more XML configuration file loaded context definition, that is to say, in the system drive load XML configuration files.

AnnotationConfigWebApplicationContext: for web applications, suitable for comments.

XmlWebApplicationContext: Loads context definitions from one or more XML configuration files in a Web application for XML configuration.

Work through XML configuration or annotations to configure the beans to be managed and the collaboration between the beans. Then load the application Context object into the Spring container, and the container can provide your application with the object management service you want. Such as tracking the ClassPathXmlApplicationContext underlying source code:

As you can see that parsing an XML file can be extended up to eight layers, you can see that the Spring container takes a holistic approach to implementing IOC.

2.3 AOP

If we want to code the calculator function, our goal is to realize the operation of addition, subtraction, multiplication and division, but how to print the log and verify the number compliance before and after each operation?

Separate reusable functional modules for logging and data validation, and then dynamically embed and execute this code where appropriate in the execution of the program. This simplifies code writing.

The business logic code does not have the code of parameters and general logic, and the business module is more concise and only contains the core business code. The code separation of business logic and general logic is realized, which is easy to maintain and upgrade, and reduces the coupling of business logic and general logic.

The code must be loaded into memory to implement the new object, so if we extract the reusable function, and then implement the common function in memory to construct a new object, it is OK.

Spring AOP(Aspect Oriented Programming) provides just another way to think about program structure to improve object-oriented Programming. If the purpose of dependency injection is to keep components cooperating with each other in a looser coupling state, AOP separates functionality across applications into reusable components. A technique for dynamically adding functionality to a program without modifying the source code at compile, load, or run time. Thus realize the isolation of business logic, improve the modular ability of code.

The core of AOP is actually dynamic proxy, if it is to achieve the interface then will use JDK dynamic proxy, otherwise use CGLIB proxy, mainly applied to deal with some crosscutting nature of system-level services, such as log collection, transaction management, security check, cache, object pool management, etc..

Spring mainly provides aspects, JoinPoint join points, PointCut pointcuts, Advice enhancements and other implementations. AOP generally has five ways to surround:

Pre-notification (@before)

Return notification (@afterRETURNING)

Exception Notification (@afterThrowing)

Post notification (@after)

Circular notification (@around) :(highest priority)

PS: In the case of multiple facets, you can use @order to specify the sequence. The smaller the number, the higher the priority.

3 Differences between JDK dynamic proxies and CGLIB proxies

JDK dynamic proxies and CGLib dynamic proxies are both the basis for implementing Spring AOP, and they are implemented in different ways.

3.1 JDK Dynamic Proxy

The characteristics of

Interface: For JDK dynamic proxies, business classes need an Interface.

Proxy: The Proxy class is dynamically generated. This class generates an instance of Proxy after calling the proxy.newProxyInstance () method. In fact, the Proxy class also exists, not just the instance of the class, but the Proxy class can be stored on the hard disk.

Method: Each Method of the business delegate class is now not statically displayed in the Proxy class.

InvocationHandler: This class first invokes the Invoke method when the business delegate class executes. The Invoke method performs the desired proxy operation, enabling repackaging of the business method.

Conclusion:

The JDK dynamic proxy class implements the InvocationHandler interface and overrides the Invoke method.

The basis of JDK dynamic proxies is reflection (method.invoke(object, parameter)) proxy.newProxyInstance ()

3.2 CGLib dynamic proxy

Features:

Using the bytecode processing framework ASM, its principle is to create a subclass for a class through bytecode technology, and in the subclass using method interception technology to intercept all calls to the parent class method, along with the potential woven into crosscutting logic.

Dynamic proxy objects created by CGLib perform much better than those created by JDK. However, CGLib takes much longer to create proxy objects than the JDK, so for singleton objects, CGLib works better than JDK because you don’t need to create objects frequently. At the same time, because CGLib is subclassed dynamically, there is no proxy for final methods.

Note:

Unlike JDK dynamic proxies, which can only do this for interfaces, CGlib can either do this for classes that don’t implement interfaces or for classes that implement interfaces.

3.3 Code implementation part

Common code:

Public interface FoodService {public void makeNoodle(); public void makeChicken(); Public implements FoodService {@override public void makeNoodle() {public implements FoodService {@override public void makeNoodle() { System.out.println("make noodle"); } @Override public void makeChicken() { System.out.println("make Chicken"); }}Copy the code

JDK dynamic proxy code:

import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxyFactory implements InvocationHandler { private Object target; public JDKProxyFactory(Object target) { super(); this.target = target; Public Object createProxy() {// 1. ClassLoader ClassLoader = target.getClass().getClassLoader(); // 2. Get the object's implementation interface Class<? >[] interfaces = target.getClass().getInterfaces(); Object newProxyInstance = proxy. newProxyInstance(classLoader, interfaces, this); return newProxyInstance; } // First argument: proxy object. Generally not used; The second parameter: the method to be enhanced; @override public Object invoke(Object proxy, Method Method, Object[] args) throws Throwable {system.out.println (" this is an enhanced method before......" ); Object invoke = method.invoke(target, args); System.out.println(" This is enhanced method after......" ); return invoke; } public static void main(String[] args) { // 1. FoodServiceImpl foodService = new FoodServiceImpl(); // create proxy object JDKProxyFactory proxy = new JDKProxyFactory(foodService); FoodService createProxy = (FoodService) proxy.createProxy(); createProxy.makeChicken(); }}Copy the code

Cglib dynamic proxy code:

import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; Public class CglibProxyFactory implements MethodInterceptor {private Object target; Public CglibProxyFactory(Object target) {super(); this.target = target; Public Object createProxy(){//1. Create Enhancer Enhancer = new Enhancer(); //2. Pass the target object's class enhancer.setsuperclass (target.getClass()); //3. Set the callback to enhancer.setcallback (this); return enhancer.create(); } // Parameter one: proxy object; Parameter 2: method to be enhanced; Parameter 3: parameters that need to be enhanced; @override public Object Intercept (Object proxy, Method Method, Object[] args, MethodProxy MethodProxy) throws Throwable {system.out.println (" this is an enhanced method before......" ); Object invoke = methodProxy.invoke(target, args); System.out.println(" This is enhanced method after......" ); return invoke; } public static void main(String[] args) { // 1. FoodServiceImpl foodService = new FoodServiceImpl(); CglibProxyFactory proxy = new CglibProxyFactory(foodService); FoodService createProxy = (FoodService) proxy.createProxy(); createProxy.makeChicken(); }}Copy the code

Spring AOP differs from AspectJ AOP

4.1 Spring AOP

Spring AOP is a runtime enhancement with the following features:

  1. Based on dynamic proxy implementation, the default interface, using the DYNAMIC proxy provided by JDK implementation, if the method is CGLIB implementation
  2. Spring AOP needs to rely on the IOC container to manage and can only work with the Spring container, implemented using pure Java code
  3. In terms of performance, Spring AOP’s performance is not as good as AspectJ’s because it is implemented based on dynamic proxies, which require generating proxy instances at container startup and add stack depth to method calls.
  4. Spring AOP addresses the most common type of AOP(method weaving) in enterprise development.

4.2 the AspectJ

AspectJ is an easy-to-use, powerful AOP framework that is compile-time enhanced and can be used alone or integrated into other frameworks, making it a complete solution for AOP programming. AspectJ requires a separate compiler, AJC.

AspectJ is static weaving, which is implemented by modifying the code to finish weaving before it is actually run, so it generates classes with no extra runtime overhead. There are usually several times to weave:

  1. Compile-time weaving: If class A adds an attribute using AspectJ and class B references it, the scenario needs to be compile-time weaving otherwise class B won’t Compile.
  2. Post-compile weaving: that’s where the.class file is generated, or the weaving jar file is generated, and we need to improve the weaving.
  3. Load-time weaving: Weaving occurs when classes are being loaded, and there are several common ways to do this

4.3 contrast

5. The BeanFactory and FactoryBean

5.1 the BeanFactory

  1. BeanFactory ends with Factory, indicating that it is a Factory class (interface). BeanFacotry is the primitive Factory in Spring.
  2. BeanFactory does not support many of Spring’s plug-ins, such as AOP functionality, Web applications, and so on. The ApplicationContext interface, derived from the BeanFactory interface, provides international access, event propagation, and more.
  3. The BeanFactory, the core of the IOC container, is responsible for producing and managing Bean objects.

5.2 FactoryBean

  1. A FactoryBean ends in Bean to indicate that it is a Bean.
  2. A FactoryBean is a factory-class interface that you can implement to customize the logic of instantiating the Bean. The FactoryBean interface plays an important role in the Spring framework. Spring itself provides over 70 FactoryBean implementations.
  3. When a Bean in an IOC container implements a FactoryBean, the Bean object obtained by getBean(String BeanName) is not an implementation of the FactoryBean. It is the object returned by the getObject() method in the implementation class. To get the implementation class of a FactoryBean, getBean(String &BeanName) is preceded by an &.

6. Spring lifecycle

The process of Spring IOC initialization and destruction of beans can be roughly divided into four parts: Bean definition, Bean initialization, Bean lifetime and Bean destruction.

The problem is that Spring provides a series of interfaces and configurations to complete the Bean initialization process if we want to fulfill our custom requirements. Take a look at the entire IOC container initialization Bean process.

In general, there are three initialization and destruction methods for custom beans:

  1. Configuration via XML or @bean

Do this using XML or @bean (initMethod=”init”, destroyMethod=”destory”).

  1. This is implemented using two annotations (the Java specification) defined by the JSR250 rules

PostConstruct: An annotation in the JDK specification to initialize a Bean after it has been created and belongs to an assignment.

PreDestroy: Notify the bean before it will be removed and clean up before the container is destroyed.

Tip: JSR is a set of specifications provided by the JDK.

  1. Implement class methods through inheritance

Implement the afterPropertiesSet() method of the InitializingBean interface, which will be called after the beanFactory has created the object and all the bean properties have been set, which is equivalent to the initialization method.

Implement the destory() method to DisposableBean, which will dispose of the singleton bean when it is destroyed

For single-instance beans, the initialization and destruction methods can be invoked normally. For multi-instance beans, the container is only responsible for initialization on invocation, but does not manage the bean, and does not call destruction when the container is closed.

Three things to watch ❤️

If you find this article helpful, I’d like to invite you to do three small favors for me:

  1. Like, forward, have your “like and comment”, is the motivation of my creation.

  2. Follow the public account “Java rotten pigskin” and share original knowledge from time to time.

  3. Also look forward to the follow-up article ing🚀

  4. [666] Scan the code to obtain the learning materials package

Space constraints, the following:Interviewer: Just 13 points about Spring (2)