How do Spring beans load dynamically

  1. Use BeanDefinitionBuilder registered bean (BeanDefinitionBuilder rootBeanDefinition), add attributes & registered bean, beanFactory.registerBeanDefinition(“testBean”, b1.getBeanDefinition());
  2. Register beans using BeanFactoryPostProcessor. GenericBeanDefinition spring BeanFactoryPostProcessor allows custom BeanDefinition, use, and then into the DefaultListableBeanFactory registration.
  3. Using GenericBeanDefinition

Interceptors in Spring, how are they different from filters, their execution order, and what are they primarily used for

Interceptor/filter /AOP

Filter: Intercepts Web access URLS. This is broader than interceptors. Filters are large collections. Is based on function callbacks

Interceptor: Intercepting urls end in action or have no suffix. Interceptors are based on dynamic proxies

AOP interceptors: Can only intercept access to Spring managed beans,

Are filters and interceptors thread-safe, and why

The Filter is initialized when the Servlet container is started, so it can be considered as a singleton. If a member variable is modified by one requesting thread, it will affect other requesting threads and therefore is considered multithreaded unsafe.

AOP core Concepts

  1. Aspect: A class is an abstraction of an object’s characteristics, and an aspect is an abstraction of a crosscutting concern
  2. Crosscutting concerns: What methods to intercept and what to do with them are called crosscutting concerns.
  3. Joinpoint: intercepted point. Since Spring only supports method type join points, join points in Spring refer to intercepted methods. In fact, join points can also be fields or constructors.
  4. Pointcut: Definition of interception of join points
  5. Advice: Advice refers to the code to be executed after intercepting the join point. Advice is preloaded. Post. exception. final. There are five types of surround notification.
  6. Target object: The target object of the proxy
  7. Weave: The process of applying facets to the target object and causing the proxy object to be created
  8. Introduction: An introduction can dynamically add methods or fields to a class at run time without modifying the code.

Explain AOP

Traditional oop development code logic from the top down, the process will produce some cross-cutting issues, our main business logic relation with these problems, will be scattered in various parts of the code, difficult to maintain, aop idea is to separate the business logic and the problem of crosscutting, achieve the goal of decoupling, enhance code reusability and development efficiency

The main application scenarios of AOP are:

  • log
  • Monitor performance
  • Access control
  • Transaction management

Implementation principles of Spring AOP

  • @ EnableAspectJAutoProxy to container (the beanFactory) registered in a AnnotationAwareAspectJAutoProxyCreator object;
  • AnnotationAwareAspectJAutoProxyCreator proxy objects created on the target object, the object, is to encapsulate the JDK and additional two technology, realize the dynamic proxy objects created (in the process of creating a proxy object will create a proxy factory first, Get all the enhancers (notification methods), inject these enhancers and target classes into the proxy factory, and then use the proxy factory to create objects);
  • The proxy object executes the target method, obtains the interceptor chain of the target method, and uses the chain mechanism of the interceptor to enter each interceptor in turn for execution

Which dynamic proxy does AOP use?

  • When the bean is implemented as an interface or a subclass of Proxy, JDK dynamic Proxy; There is no interface and Spring uses CGLIB to generate proxy objects.
  • JDK dynamic proxies mainly involve two classes in the java.lang.Reflect package: Proxy and InvocationHandler.
  • Proxy uses the InvocationHandler interface (which defines crosscutting logic) to dynamically create Proxy objects for the target class.

How does Spring address loop dependencies

How do I detect circular dependencies? The Bean can be marked at creation time, and if the recursive call comes back and finds that the Bean is being created, it indicates that the loop is dependent.

The cycle dependency scenarios in Spring are:

  • Constructor loop dependencies
  • Property cyclic dependencies
  • SingletonObjects: the first level cache, which holds instantiated singletonObjects; EarlySingletonObjects: the second level cache, which holds pre-exposed singleton objects; SingletonFactories: The third-level cache that holds object factories of objects to be instantiated
  • Spring first fetches beans from the level-1 cache singletonObjects when they are created. If not, and the object is being created, then it is fetched from the earlySingletonObjects cache, or from the singletonFactories cache (after the Bean calls the constructor to instantiate, even if the properties are not filled, The object can be located in the heap according to the object reference, which is based on the principle of Java reference passing), and then moved from the level 3 cache to the level 2 cache. After it is fully initialized, it can be put into the level 1 cache for other use.
  • Because the constructor is executed before the singletonFactories level 3 cache is added, the constructor’s loop dependency cannot be resolved.
  • Constructor looping dependency workaround: Use @lazy annotations in constructors for Lazy loading. When a dependency is injected, the proxy object is injected first, and then the object is created when it is used for the first time.

What is the difference between the BeanFactory interface and the ApplicationContext interface?

  • BeanFactory: BeanFactory is a primitive, older Factory in Spring. Because of its antiquity, BeanFactory does not support Spring plug-ins, such as AOP, Web applications, etc.
  • ApplicationContext: ApplicationContext is a subclass of BeanFactory, and since the old BeanFactory doesn’t meet the needs of the ever-changing Spring, ApplicationContext basically takes over the job of BeanFactory. To work in a more framework oriented way and to layer and implement inheritance of context, and to extend functionality on this basis:
    • Unified access to resource files.
    • Provides events to register beans in listeners.
    • Load multiple configuration files simultaneously.

Introduce the understanding of Spring transactions?

The Spring framework provides a uniform set of abstractions for transaction management with the following benefits:

  1. Unified programming model across different transaction apis, whether you are using JDBC, JTA, JPA, Hibernate.
  2. Support for declarative transactions
  3. Simple transaction management API
  4. Integrates perfectly with Spring’s data access abstraction layer

Spring’s transaction management is implemented using AOP

What about Spring’s transaction implementation?

zhuanlan.zhihu.com/p/54067384

www.cnblogs.com/leeSmall/p/…

The seven modules of the Spring framework

  • Spring Core: The most basic part of the framework, which provides an IoC container for managing beans.
  • Spring Context: Inherits BeanFactory, provides Context information, extends JNDI, EJB, email, internationalization, and more.
  • Spring DAO: Provides a JDBC abstraction layer and a declarative transaction management approach.
  • Spring ORM: Provides JPA, JDO, Hibernate, MyBatis and other ORM mapping layers.
  • Spring AOP: Integrates all AOP capabilities
  • Spring Web: Provides context information for basic Web development, and existing Web frameworks, such as JSF, Tapestry, Structs, and so on, provide integration
  • Spring Web MVC: Provides a fully functional implementation of model-View-Controller for Web applications.

The Bean defines five scopes

  • Singleton (singleton)
  • Prototype
  • request
  • session
  • global session

Spring IOC Initialization process?

Resource location is to find a user-defined bean resource, BeanDefinitionReader Load BeanDefinitionReader Read and resolve resources located by Resource into beanDefinition through ResourceLoader Loaded into ioc (maintained BD via HashMap) BeanDefinitions registration registers these BeanDefinitions with the IOC container, implemented via BeanDefinitionRegistery

BeanDefinition loading process?

Define BeanDefinitionReader parsing XML document BeanDefinitionDocumentReader parsing the document into a beanDefinition

DI dependency injection process? (Instantiate, handle dependencies between beans)

Procedure After Ioc initialization, the dependency injection process is triggered the first time a user requests a Bean from the Ioc container

  • If lazy-init=true, the bean will be initialized on the first getBean. If lazy-init=false, the singleton bean will be initialized directly on container startup.
  • Call beanfactory.getBean () to generate the bean’s;
  • The bean generation process uses the decorator pattern to produce beans that are beanWrapper (bean enhancements);

How does dependency injection handle dependencies between beans?

This is done by using placeholders when beanDefinition is loaded if the bean has a dependency. When getBean is called, if a placeholder is encountered, the bean is fetched from ioc and injected into this instance

The life cycle of the Bean?

  • Instantiated beans: The Ioc container instantiates them by getting information from the BeanDefinition object, which is wrapped in a BeanWrapper object
  • Set object properties (DI) : Property dependency injection is done through the interface provided with BeanWrapper to set properties;
  • Inject the Aware interface (BeanFactoryAware, which can be used to get other beans, ApplicationContextAware) : Spring detects whether the object implements the xxxAware interface and injects the associated xxxAware instance into the bean
  • BeanPostProcessor: custom processing (pre processing and post processing)
  • InitializingBean and init-method: Perform our own defined initialization methods
  • use
  • Destroy: Bean destruction

IOC: Inversion of control: The creation of objects is managed by Spring. DI (dependency injection) : When Spring creates an object, it injects the properties that the object depends on into the class.

Spring’s IOC injection approach

Constructor injection setter methods inject annotation injection interface injection

What design patterns are used in Spring?

  • Factory pattern: Spring’s BeanFactory is an example of the simple factory pattern, passing in unique identifiers to get bean objects;
  • Singleton pattern: provides a global access point BeanFactory;
  • Proxy mode: The principle of AOP functionality is to use proxy mode (1, JDK dynamic proxy. 2. CGLib bytecode generation technology agent.
  • Decorator mode: Dependency injection requires BeanWrapper;
  • Observer pattern: A common place in Spring for the Observer pattern is the listener implementation. Such as ApplicationListener.
  • Policy pattern: Bean instantiation determines how the Bean instance is initialized (reflection or CGLIB dynamic bytecode generation)

For springMVC process:

  1. User requests are sent to DispatcherServlet, which calls the HandlerMapping processor mapper.
  2. HandlerMapping finds the corresponding processor according to XML or annotations and generates the processor object to return to DispatcherServlet.
  3. The DispatcherServlet calls the corresponding HandlerAdapter;
  4. The HandlerAdapter ADAPTS to call the specific handler to handle the request, generating a ModelAndView that is returned to the DispatcherServlet
  5. The DispatcherServlet passes the ModelAndView to ViewReslover and parses the generated View and returns it to the DispatcherServlet.
  6. DispatcherServlet renders View according to View; ->DispatcherServlet->HandlerMapping->Handler ->HandlerAdapter Handler ->ModelAndView ->DispatcherServlet->ModelAndView->ViewReslover->View ->DispatcherServlet-> Return to customer