The advantages of the Spring

The Spring framework provides comprehensive infrastructure support for developing Java applications. Many modules are provided out of the box, which simplify development, improve development efficiency and improve system maintainability.

  • Spring is an open source, free framework (container)
  • Spring is a lightweight, non-invasive framework
  • Inversion of Control (IOC), Aspect Oriented Programming (AOP)
  • Support transaction processing, support for framework integration

Spring is a lightweight IOC and AOP framework

Cons: The Spring framework provides the flexibility to configure beans in a variety of ways, such as XML, Annotations, and JavaConfig. As the number of features increases, so does the complexity, and configuring Spring applications becomes tedious and error-prone.


Advantages of Spring Boot

SpringBoot is basically an extension of the Spring framework that removes the complexity of setting up Spring application configurations, paving the way for a faster, more efficient development ecosystem.

  • Faster start for all Spring developers
  • Out of the box, various default configurations are provided to simplify project configuration
  • Embedded containers simplify Web projects
  • There is no requirement for redundant code generation and XML configuration

Important Spring modules

  • Spring Core: Basic, it can be said that all of Spring’s other functions depend on this library. It mainly provides IoC dependency injection function.
  • Spring Aspects: This module provides support for integration with AspectJ.
  • Spring AOP: Provides a section-oriented programming implementation.
  • Spring JDBC: Java database connection.
  • Spring JMS: Java messaging service.
  • Spring ORM: Used to support ORM tools such as Hibernate.
  • Spring Web: Provides support for creating Web applications.
  • Spring Test: Provides support for JUnit and TestNG tests.

Dependency injection

  • Constructor injection
  • Set injection (common)
    • Dependencies: The creation of bean objects depends on the container
    • Injection: All properties in the bean object are injected by the container
  • Annotation injection

What extensibility does Spring provide

  1. Add some functionality before the object is created.
  2. Add some functionality before container initialization.
  3. Emit different events at different stages to accomplish some function.
  4. Abstract out a bunch of interfaces to help with extension.
  5. Interface oriented programming.

Scope of beans in Spring

  • Singleton: There is only one instance bean in the Spring container, and beans in Spring are singleton by default.
  • Prototype: Returns a new instance each time the bean is called from the container, i.e. each time getBean() is called, new XXXBean() is executed.
  • Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
  • Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.
  • Global-session: the global session scope, which is only meaningful in portlet-based web applications, is no longer available in Spring5. Portlets are small Java Web plug-ins that can generate snippets of semantic code, such as HTML. They are based on portlet containers and can handle HTTP requests like servlets. However, unlike servlets, each portlet has a different session.

The life cycle of beans in Spring

  • The Spring container loads and parses the configuration files, generating beanDefintions one by one, which are managed by BeanDefintionRegistry.
  • Then, if a bean implements the Aware interface, such as BeanNameAware, BeanFactoryAware, etc., then the corresponding set method is called to set the value. For example, when implementing the BeanNameAware interface, the factory calls the setBeanName() method using the bean ID to pass in the bean name, so that some information can be passed in. Similarly, if any other Aware interface is implemented, the corresponding set method is called.
  • If the bean association of any BeanPostProcessors, call postProcessBeforeInitialization () method.
  • If the bean specifies the init() method, then it is called.
  • If the bean association of any BeanPostProcessors, call postProcessAfterInitialization () method.
  • When you close the bean factory, the destroy() method is called if the bean implements the DisposableBean interface. If the bean specifies destroy(), the specified destroy() method is called.

A detailed version:

  • ResouceLoader loads the configuration information
  • BeanDefintionReader parses the configuration information and generates beanDefintions one by one
  • BeanDefintion is managed by BeanDefintionRegistry
  • Spring BeanFactoryPostProcessor configuration information for processing (i.e., processing configuration information, usually by is accomplished to realize)
  • Instantiate the Bean
  • If the BeanConfiguration/ImplementationInstantiationAwareBean, the corresponding method is called
  • Use BeanWarpper to configure properties between objects (dependencies)
  • If the BeanConfigured/implementedAware interface, the corresponding method is called
  • Called if the Bean is configured with the before method of BeanPostProcessor
  • If the Bean is configuredinit-methodOr implement InstantiationBean, the corresponding method is called
  • Called if the Bean is configured with the BeanPostProcessor’s after method
  • Put objects into a HashMap
  • Finally, if you have configured the methods destroy or DisposableBean, execute the destruction operation

Automatic assembly of beans in Spring

Spring automatically finds and automatically assembles properties to the bean in the context. Autowire using tags:

  • Byname: Automatically looks up the bean ID in the container context after the set method of its own object.
  • Bytype: Automatically looks up beans in the container context that have the same property type as its own object.

The difference between @Resource and @autowired

  • @Resource is a Java annotation and @AutoWired is a Spring annotation
  • It’s all autowiring, and you can put it on a property field
  • @autoWired is implemented by byType and must require the object to exist. “Common”
  • @resource is implemented as byName by default, or byType if no name can be found. If neither is found, an error is reported.

ApplicationContext architecture analysis

ApplicationContext is an interface that inherits a number of interfaces:

  • BeanFactory: The top-level interface to Spring’s managed beans. ApplicationContext inherits two subclasses of BeanFactory: HierarchicalBeanFactory and ListableBeanFactory. HierarchicalBeanFactory is a HierarchicalBeanFactory that returns the parent bean factory via getparentBeanFactory(). ListableBeanFactory implements enumeration methods that list all bean objects in the current BeanFactory without fetching them one by name.
  • ApplicationEventPublisher: encapsulates event publishing function interface, event messages sent to the event listener. This interface provides a publishEvent() that notifies all listeners registered in the application.
  • ResourcePatternResolver: Inherits the ResourceLoader interface, which is the policy interface that resolves the location schema into Resource objects. Inherited from ResourceLoader, which is Spring’s top-level interface for loading resources and for loading resource files.
  • MessageSource: Policy interface for parsing messages to support functions such as internationalization.
  • EnvironmentCapable: Provides the current system Environment component.

Spring is a very good framework with good structure design and interface abstraction. Each interface has a single function and is highly abstract from specific functions to modules. Almost every set of interfaces provides a default implementation (defaultXXX). For the ApplicationContext architecture, it inherits many of Spring’s core interfaces and can provide a relatively complete Spring container for the client. Interface ConfigurableApplicationContext, extending the ApplicationContext interface again provides life cycle management functions. Abstract class AbstractApplicationContext interface provides most of the default implementation of a complete set of, in which “is not easy to change the part of” encapsulation, through the way of “combination” entrust “easy to change the function of the other classes, At the same time, the template method pattern is used to open the implementation of some methods to be realized by the subclass, so as to realize the design principle of “open to extension, closed to modification”.


What is the relationship between BeanFactory and ApplicationContext?

ApplicationContext is a Spring container, also known as an ApplicationContext. It inherits BeanFactory and is also an extended upgrade of BeanFactory. Since the structure of the ApplicationContext distinguishes it from the BeanFactory, the main differences are:

  1. Inheriting MessageSource to provide a standard access strategy for internationalization;
  2. Inheritance ApplicationEventPublisher, provide a powerful event mechanism;
  3. Extension ResourceLoader, can be used to load multiple resources, flexible access to different resources;
  4. Support for Web applications.


Spring loop dependency issues

Circular dependencies are circular references, where two or more singleton beans hold each other to form a ring. Prototype scenarios do not support loop dependencies, and AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory class AbstractBeanFactory [Constructor injection does not solve loop dependencies] example:

@Component
public class A {
  private B b;
}
@Component
public class B {
  private A a;
}
Copy the code

Spring bean instantiation is through the ApplicationContext. GetBean () method. If you want to get object dependent on another object, so the first creates the object, and then through the recursive call ApplicationContext. The getBean () method to get the dependent objects, finally will obtain the object into the current object.

How to deal with cycle dependencies: First, Spring maintains three maps internally, which are commonly referred to as level 3 caches.

  • SingletonObjects: Commonly known as “singleton pools” or “containers”, caches where singleton beans are created. BeanName – > instance
  • SingletonFactories: The original factory to cache singleton beans. BeanName – > the factory
  • EarlySingletonObjects: Caches beans created earlier, that is, beans in this Map are not complete (half-baked) or even called “beans”, just instances. BeanName — > instance(semi-finished product)

The last two maps are actually “stepping-stone” level maps that are used for Bean creation and then removed.

The main solution to loop dependencies is the **doCreateBean()** method. = =

Specific execution process (take the above two classes for example) :

  1. Instantiate A into doCreateBean(), A method that handles loop dependencies, and expose A’s beanFactory ahead of time.
    • Singletons whether prior exposure is requiredIf the following three conditions are met, the addSingletonFactory() method is executed.
      • Is this BeanDefinition a singleton
      • Whether the container allows cyclic dependencies
      • Determines whether the bean is under creation.
  2. Put A’s beanFactory into the SingletonFactory cache with the addSingletonFactory() method.
  3. The next step is to populate the property, which is implemented by the populateBean() method. When populating the property, if B is found, the first step is to check the cache to see if there is an instance cache of B. If there is no instance cache of B, instantiate B.
  4. Instantiating B exposes B’s beanFactory and stores it in the singletonFactories cache.
  5. To fill B, found A, according to the set singletonsCurrentlyInCreation, found A already in creation, from A factory output “early” beanA, moved to earlySingletonObjects cache. Delete the beanFactory of A from singletonFactories.
  6. And then you take A directly from the cache, inject it into B, add B to the singletonObjects cache, return B, inject it into A, add A to the singletonObjects cache, return A.


The difference between BeanFactory and FactoryBean

The BeanFactory: The BeanFactory is the basic IOC container, responsible for producing and managing beans. It provides the basic specification for other IOC containers, such as the ApplicationContext, that implement the BeanFactory and add additional functionality on top of it.

FactoryBean: a FactoryBean that creates or decorates the generation of objects. Its implementation is somewhat similar to the factory and decorator patterns in the design pattern. It can produce an object when needed, and not just itself, it can return an instance of any Bean. If the Bean implements this interface, it will be used as a factory to expose the object, rather than directly as the Bean instance to expose itself. Spring provides a FactoryBean factory class interface that users can implement to customize the logic of instantiating beans. One of the most typical uses of FactoryBeans in Spring is to create proxy objects for AOP.


What design patterns are used in the Spring framework?

  • Factory design pattern: Spring uses factory mode to passBeanFactory,ApplicationContextCreate the bean object. The essence of the simple factory pattern is that a factory class dynamically decides which product class should be created based on the parameters passed in. The BeanFactory in Spring is an embodiment of the simple factory pattern. Bean objects are obtained by passing in a unique identifier, but whether this is created after or before the parameters are passed in depends on the case.
  • Proxy design pattern: Implementation of Spring AOP functionality.
  • Singleton design pattern: Beans in Spring are singleton by default. Ensure that a class has only one instance and provide a global access point to it, BeanFactory.
  • Template method pattern: in the SpringjdbcTemplate,hibernateTemplateClasses that operate on databases that end in Template use the Template pattern.
  • Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern. Such as ApplicationListener.
  • Adapter mode: Converts the interface of a class into another interface desired by the customer. The Adapter pattern enables classes to work together that would otherwise not work together due to interface incompatibilities. The adapter pattern is used in Spring AOP enhancements or Advice, and HandlerAdapter adapter pattern adaptation is used in Spring MVCController.

Isolation levels for Spring transactions (five)

Five constants representing the isolation level are defined in the TransactionDefinition interface:

  • ISOLATION_DEFAULT: Use the default isolation level of the back-end database, REPEATABLE_READ isolation level used by Mysql and READ_COMMITTED isolation level used by Oracle.
  • ISOLATION_READ_UNCOMMITTED: Minimum isolation level that allows uncommitted data changes to be read, possibly resulting in dirty reads, illusory reads, or unrepeatable reads.
  • ISOLATION_READ_COMMITTED: Allows concurrent transactions to read data that has already been committed. Dirty reads can be prevented, but phantom or unrepeatable reads can still occur.
  • ISOLATION_REPEATABLE_READ: Multiple reads of the same field are consistent, unless the data is modified by the transaction itself. This can prevent dirty reads and unrepeatable reads, but phantom reads are still possible.
  • ISOLATION_SERIALIZABLE: The highest isolation level, fully compliant with ACID characteristics. All transactions are executed one by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this severely affects the performance of the program.

Transaction propagation behavior of Spring Transactions (seven)

Transaction propagation behavior is designed to solve the transaction problem of business layer methods calling each other.

Cases that support the current transaction:

  • * * TransactionDefinition. PROPAGATION_REQUIRED: * * existing transaction, to join the transaction; If there are no transactions currently, create a new transaction.
  • TransactionDefinition. PROPAGATION_SUPPORTS: existing transaction, to join the transaction; If there is no transaction currently, it continues in a non-transactional manner.
  • * * TransactionDefinition. PROPAGATION_MANDATORY: * * existing transaction, to join the transaction; If there is no transaction, an exception is thrown.

The current transaction is not supported:

  • TransactionDefinition. PROPAGATION_REQUIRES_NEW: create a new transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NOT_SUPPORTED: run way of transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NEVER: run way of transaction, if the current transaction, throw an exception.

Other information:

  • TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, then create a transaction for the current affairs of nested transactions to run; If there is no transaction currently, a new transaction is created.

How exactly are transactions implemented in Spring

  1. If Spring does not specify a transaction isolation level, the database default transaction isolation level is used. When Spring specifies a transaction isolation level, it changes the transaction isolation level to the specified value in the code. When the database does not support the isolation level specified by Spring, the effect will be based on the database (for example, using the MyISAM engine).
  2. The underlying layer of Spring transactions relies on database transactions, implemented using AOP at the code level. MySQL has an isolation level for transactions. Only InnoDB has transactions, using undo log and redo log.
  3. Implement declarative transactions through AOP.

IOC (Focus)

IOC is inversion of control. It’s really a thought.

  • The traditional way of development is to manually create an object of B in class A using the new keyword.
  • Development using IoC thinking: instead of creating objects through the new keyword, the IoC container (the Spring framework) helps us instantiate objects. Which object we need can be taken directly from the IoC container.

IOC gives the Spring framework control over the manually created objects in the program. The IoC container is the vehicle Spring uses to implement IoC. The IoC container is like a factory. When we need to create an object, we just need to configure the configuration file/annotations, and Spring will automatically inject and create the object for us. Never mind how the object was created. Spring also leaves the dependencies between objects to the IoC container to manage. This greatly simplifies application development. For example, in a real project, a Service class might have hundreds of classes as its underlying class. If we need to manually instantiate the Service, you might have to know the constructors of all the underlying classes of the Service, which would be very troublesome. With IoC, all you need to do is configure the configuration file and reference it where necessary, greatly reducing the coupling between objects, increasing the maintainability of the project and making it easier to develop. Principle: Through reflection technology. Spring describes beans and their dependencies through a configuration file, and uses reflection techniques to instantiate beans and establish dependencies between beans.


AOP (emphasis)

AOP (aspect oriented programming) to those who has nothing to do with the business logic of the common code (e.g., performance monitoring, log management, access control, etc.) encapsulated, so where needed can be invoked at any time, it can reduce the duplicated code system, reduce the coupling between modules, and is conducive to future expansibility and maintainability. Principle: Through the implementation of proxy, proxy is mainly divided into static proxy and dynamic proxy.

  • Static Proxy (AspectJ) : Enhancements to each method of the target object are manual, inflexible (for example, when new methods are added to the interface, both the target object and the proxy object need to be modified) and cumbersome (you need to write a separate proxy class for each target class). In Spring, static proxying is where the AOP framework generates AOP proxy objects at compile time, weaving aspects into bytecode at compile time, and is therefore also known as compile-time enhancement. And requires a specific compiler to handle it.
  • Dynamic proxy (Spring AOP) : Dynamic proxy means that the AOP framework does not modify the bytecode. Instead, the runtime temporarily generates an AOP proxy object in memory that contains all the methods of the target object, enhances them at specific pointcuts, and calls back the methods of the original object. In contrast to static proxies, it does not require specific compiler processing.

Spring AOP is dynamic proxy, and there are two main ways: JDK dynamic proxy and CGLIB dynamic proxy.

  • JDK dynamic proxy:JDK dynamic proxy passedreflectionTo receive the proxied class and require that the proxied class be implementedinterface. If the target class does not implement the interface, Spring AOP chooses to use CGLIB to dynamically proxy the target class.
    • Define an interface and its implementation class;
    • The customInvocationHandlerPay equal attention to writinginvokeMethods,invokeMethod we call native methods (methods of the propped class) and customize some processing logic;
    • throughProxy.newProxyInstance(ClassLoader loader,Class<? >[] interfaces,InvocationHandler h)Method to create a proxy object;
  • CGLIB dynamic proxy:Bytecode is a bytecode generation library that allows us to modify and generate bytecode dynamically at run time, using bytecode technology at the bottom. Additional is throughinheritanceCglib dynamically generates subclasses at run time that inherit all the public methods of the parent class, and then can override those methods and enhance them as they are overridden. Note: Therefore, if a class is final, it cannot use CGLIB as a dynamic proxy.
    • Define a class;
    • The customMethodInterceptorPay equal attention to writinginterceptMethod,interceptMethods used to intercept enhanced propped classes, and in JDK dynamic proxiesinvokeMethods are similar;
    • throughEnhancer.create()Create a proxy class;

JDK dynamic proxy and CGLIB dynamic proxy comparison

  1. JDK dynamic proxies can only proxy classes that implement interfaces, whereas CGLIB can proxy classes that don’t implement any interfaces. In addition, CGLIB dynamic proxies intercept method calls of proxied classes by generating a subclass of the proxied class, so classes and methods declared as final cannot be proxied.
  2. In most cases, the JDK dynamic proxy is superior in terms of both efficiency, and this advantage becomes more apparent as JDK versions are upgraded.

Benefits of the proxy model

  • You can make the operation of real characters more pure, without having to focus on some common business.
  • The common business is entrusted to the agent role, realizing the division of business!
  • When common services expand, it facilitates centralized management.
  • A dynamic proxy class represents an interface, usually a corresponding class of services.
  • A dynamic proxy class can proxy multiple classes, as long as the implementation is similar to the same interface.

Automatic assembly of Springboot (emphasis)

The first @springBootConfiguration annotation, which inherits from @Configuration, does the same thing, marking the current class as a Configuration class. @ComponentScan is used to automatically scan and load qualified components, so there is only one annotation left that may be associated with automatic configuration, is ** @enableAutoConfiguration **, this means that automatic configuration is enabled.

Then the annotations by @ Import annotations AutoConfigurationImportSelector Import a selector class components, the class has a method getCandidateConfigurations () to obtain the candidate configuration, This method is called again SpringFactoriesLoader. LoadFactoryNames () the static method. The loadSpringFactories () method is used to retrieve the meta-INF/spring.factories () resource. The Javaconfig configuration class contains the fully qualified name of the Javaconfig configuration class and the beans that are injected into it. So automatic assembly truly from the classpath to search all the meta-inf/spring. Factories configuration files, and the corresponding org. Springframework. Boot. The autoconfigure configuration items under the package, Instantiated by reflection into an IOC container Configuration class in JavaConfig form corresponding to @Configuration, these are then aggregated into an instance and loaded into the IOC container.

Of course, so many auto-configuration classes must be effective under certain conditions; That is, we loaded so many configuration classes, but not all of them worked. Springboot uses **@Conditional** annotations and extended annotations to determine whether a condition is valid. If all conditions are valid, the class is automatically configured; otherwise, it will not take effect. The AopAutoConfiguration class, for example, will not import this configuration class if you do not have an AOP package.

Conclusion:

  1. SpringBoot gets the specified value (the fully qualified name of the configuration class) from meta-INF/Spring.Factories in the classpath when it starts.
  2. Import these values into the container as auto-configuration classes, and the auto-configuration classes take effect, helping us do auto-configuration work, things we used to need auto-configuration, now SpringBoot does for us;
  3. The entire J2EE, solution, and auto-configuration package is in the Springboot-Autoconfigure JAR;
  4. It imports a number of auto-configuration classes (xxxAutoConfiguration) into the container, which is to import all the components needed for this scenario into the container and configure them;
  5. With the automatic configuration class, we do not need to manually write configuration injection function components;

Sometimes, we need to change the property value even though the auto-configuration class is in effect. In this case, we can change the property value through the configuration file.

  • Once the auto-configuration class is in effect, it adds various components to the container.
  • The properties of these components are obtained from the corresponding xxxProperties classes, each of which is bound to the configuration file;
  • All properties that can be configured in a configuration file are encapsulated in the xxxxProperties class;
  • What can be configured in a configuration file can refer to the property class corresponding to a particular function.

Essence:

  1. SpringBoot loads a large number of auto-configuration classes when it starts;
  2. Let’s see if the functionality we need is in the automatic configuration class written by default in SpringBoot.
  3. As long as the component we want to use exists in it, we don’t need to configure it manually; If the auto-configuration class is not implemented, we need to manually specify it in the configuration file. This configuration file is bound to xxxProperties, so when adding components to the auto-configuration class in the container, we get some properties from the xxxProperties class.

**xxxAutoConfigurartion: Automatic configuration class; ** Adds components to the container

XxxProperties: encapsulates the related properties in the configuration file.

Key annotation: @SpringBootApplication, which is a composite annotation:

  • @ComponentScan: Automatically scans and loads qualified components or beans, and loads the bean definition into the IOC container.
  • @SpringBootConfiguration: Class annotated with it, indicating that the class is a configuration class and a component in Spring. So there’s this annotation on the launch class, table name which is both the configuration class and the component of Spring that launches the application.
  • @enableAutoConfiguration (Key) : Enable the automatic assembly function
    • @autoConfigurationPackage: Automatic configuration package
    • @ import: Spring annotations @ import, bottom to import a component in the container, import a selector AutoConfigurationImportSelector. Class

What does the SpringApplication class mainly do

  1. Determine whether the type of application is a normal project or a Web project
  2. Find and load all available initializers into the Initializers property
  3. Find all application listeners and set them to the Listeners properties
  4. Infer and set the definition class of the main method to find the running main class

Spring MVC

The Spring MVC framework provides a model-view-controller architecture. The MVC pattern helps separate different aspects of an application, such as input logic, business logic, and UI logic, while providing low coupling between all these elements.

Workflow of DispatcherServlet?

  1. The DispatcherServlet represents the front-end controller and is the control center of the whole SpringMVC. The user sends a request, which is received and intercepted by the DispatcherServlet.
  2. The DispatcherServlet invokes HandlerMapping, also known as the processor mapper, based on the request information.
  3. HandlerMapping passes the request information to the corresponding HandlerExecution, which parses the specific Handler to find the controller based on the URL.
  4. HandlerExecution passes parsed controller information to the DispatcherServlet.
  5. The DispatcherServlet then passes the received controller information to the HandlerAdapter, which represents the processor adapter that executes the Handler according to specific rules.
  6. The HandlerAdapter lets the specific controller execute it.
  7. After the Controller processes the information (usually to perform specific business), it returns the specific execution information to the HandlerAdapter, such as ModelAndView.
  8. The HandlerAdapter passes the view logical name and model to the DispatcherServlet.
  9. The DispatcherServlet calls the ViewResolver to resolve the logical view name passed by the HandlerAdapter.
  10. The view parser passes the parsed logical view name to the DispatcherServlet.
  11. The DispatcherServlet invokes specific views based on the view results parsed by the view parser.
  12. The view is responsible for returning the rendered results to the client.

The differences between Model, ModelMap, and ModelAndView

Model: There are only a few methods available for storing data, simplifying the operation and understanding of Model objects for beginners.

ModelMap: inherits the Methods and features of LinkedHashMap, in addition to implementing some of its own methods.

ModelAndView: Can store data at the same time, can set the returned logical view, control view layer jump.


What’s the difference between a filter and an interceptor?

Filters: When you have a bunch of things, you only want to select certain things that fit your requirements. The tool that defines these requirements is the filter.

Interceptor: When a process is in progress, you want to interfere with its progress, or even stop it. This is what interceptors do.

  • Different implementation principles
    • Filter: based on the callback function implementation.
    • Interceptor: Implemented based on Java reflection mechanism (dynamic proxy).
  • Different scope of use
    • Filters: The Filter interface is implemented under the Javax. servlet package, which means it relies on web containers such as Tomcat, so it can only be used in Web applications.
    • Interceptor: It is a Spring component, managed by the Spring container, independent of containers such as Tomcat, and can be used independently. Not only can be applied in web programs, but also can be used in Application, Swing and other programs.
  • Different trigger times
    • Filters: The Filter is preprocessed after the request enters the container, but before it enters the servlet, and the request ends after the servlet has processed it.
    • Interceptor: The Interceptor is pre-processed after the request enters the servlet, but before it enters the Controller, where it renders the corresponding view.
  • The scope of the intercepted request is different
    • Filters: Can act on almost any request coming into the container.
    • Interceptor: Interceptors only work on requests in Controller or requests to access resources in static directories.
  • Injecting beans is different
    • Filters: Inject beans at any time without problems.
    • Interceptor: An error is reported when a Service is injected into an Interceptor. This is because the Service has not been loaded into the Spring IOC container at the time of loading. Therefore, we can manually inject the Interceptor into the Spring container before registering the Interceptor.
  • Control execution sequence is different
    • Filters: Filters use the @order annotation to control the Order of execution. Filters use the @order annotation to control the level of the filter. The lower the value, the higher the level, the earlier the execution.
    • Interceptor: The default execution Order of interceptors, which is the Order in which they are registered, can also be manually controlled by Order, with smaller values being executed first.