6. Spring principle

06Spring principle explanation

1. What is the Spring framework and which modules are included in the Spring framework

​ Spring is an open source framework, and Spring is a lightweight Java development framework. It was created to solve the complexity of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows users to choose which component to use, while providing an integrated framework for J2EE application development. Spring uses basic JavaBeans to accomplish things that previously could only be done by EJB. However, the use of Spring is not limited to server-side development. From the perspective of simplicity, testability, and loose coupling, any Java application can benefit from Spring. The core of Spring is inversion of control (IoC) and aspect-oriented (AOP). Simply put, Spring is a hierarchical full-stack (one-stop) lightweight open source framework.

Mainly included modules:

2. Advantages of Spring Framework

​ 1. Spring simplifies enterprise-level Java development through DI, AOP, and elimination of boilerplate code

​ 2. In addition to the Spring framework, there is a huge ecosystem built on the core framework, which extends Spring to different fields, such as Web services, REST, mobile development, and NoSQL

​ 3. Low intrusion design, code pollution is extremely low

​ 4. Independent of various application servers, applications based on the Spring framework can truly realize the promise of Write Once, Run Anywhere

​ 5. Spring's IoC container reduces the complexity of business object replacement and improves the decoupling between components

​ 6. Spring's AOP allows centralized processing of some common tasks such as security, transactions, logs, etc., thereby providing better reuse

​ 7. Spring's ORM and DAO provide good integration with third-party persistence layer frameworks, and simplify the underlying database access

​ 8. Spring's high degree of openness does not force applications to completely depend on Spring. Developers are free to choose part or all of the Spring framework.

3. What are IOC and DI?

​ Inversion of control means that the application itself is not responsible for the creation and maintenance of dependent objects. The creation and maintenance of dependent objects is the responsibility of the external container. In this way, the application transfers control to the external container, and the transfer of control is inversion of control.

​ Dependency injection refers to: during the running of the program, the external container dynamically injects dependent objects into the component, such as: generally, through constructor injection or setter injection.

4. Describe the initialization process of the Spring IOC container

​ The initialization of the Spring IOC container can be simply divided into three processes:

​ The first process is Resource resource positioning . This Source refers to the resource location of BeanDefinition. This process is the process in which the container finds data, just like the water in a bucket needs to find the water first.

​ The second process is the loading process of BeanDefinition . This loading process represents the user-defined Bean as a data structure inside the Ioc container, and the data structure inside the container is BeanDefition.

​ The third process is the process of registering these BeanDefinitions with the IOC container . This process is the process of saving the previous BeanDefition to the HashMap.

5. What is the difference between BeanFactory and FactoryBean?

  •     scenes to be used:

    • Get Bean (byName or byType) from the Ioc container
    • Retrieve whether the specified Bean is contained in the Ioc container
    • Determine whether the Bean is a singleton
  • FactoryBean is a Bean. This Bean is not a simple Bean, but a factory Bean that can produce or modify objects. Its implementation is similar to the factory pattern and decorator pattern in the design pattern.

    scenes to be used

    • ProxyFactoryBean

6, the similarities and differences between BeanFactory and ApplicationContext

 

the same:

  • Spring provides two different IOC containers, one is BeanFactory and the other is ApplicationContext, both of which are Java interfaces. ApplicationContext inherits from BeanFactory (ApplicationContext inherits from ListableBeanFactory.
  • They can all be used to configure XML attributes and also support automatic injection of attributes.
  • While ListableBeanFactory inherits from BeanFactory), BeanFactory and ApplicationContext both provide a way to obtain beans using getBean("bean name").

different:

  • When you call the getBean() method, the BeanFactory only instantiates the bean, and the ApplicationContext instantiates the singleton bean when the container is started, and does not wait for the getBean() method to be instantiated again.
  • BeanFactory does not support internationalization, i18n, but ApplicationContext provides support for it.
  • Another difference between BeanFactory and ApplicationContext is the ability to publish events to beans registered as listeners.
  • A core implementation of BeanFactory is XMLBeanFactory and a core implementation of ApplicationContext is ClassPathXmlApplicationContext. For the environment of Web container, we use WebApplicationContext and add the getServletContext method.
  • If you use automatic injection and use BeanFactory, you need to use API to register AutoWiredBeanPostProcessor, if you use ApplicationContext, you can use XML for configuration.
  • In short, BeanFactory provides basic IOC and DI functions, while ApplicationContext provides advanced functions. BeanFactory can be used for testing and non-production use, but ApplicationContext is a more feature-rich container implementation and should be better than BeanFactory

7. What is the life cycle of Spring Bean?

to sum up:

(1) Instantiate Bean:

For the BeanFactory container, when a client requests an uninitialized bean from the container, or needs to inject another uninitialized dependency when initializing the bean, the container will call createBean for instantiation. For the ApplicationContext container, when the container is started, all beans are instantiated by obtaining the information in the BeanDefinition object.

(2) Set object properties (dependency injection):

The instantiated object is encapsulated in the BeanWrapper object, and then, Spring completes dependency injection based on the information in the BeanDefinition and the attribute setting interface provided by the BeanWrapper.

(3) Processing Aware interface:

Next, Spring will detect whether the object implements the xxxAware interface, and inject the relevant xxxAware instance into the Bean:

① If this Bean has implemented the BeanNameAware interface, the setBeanName(String beanId) method implemented by it will be called, and what is passed here is the id value of the Bean in the Spring configuration file;

② If this Bean has implemented the BeanFactoryAware interface, it will call the setBeanFactory() method it implements, passing the Spring factory itself.

③If this Bean has implemented the ApplicationContextAware interface, it will call the setApplicationContext(ApplicationContext) method and pass in the Spring context;

(4)BeanPostProcessor:

If you want to perform some custom processing on the Bean, you can make the Bean implement the BeanPostProcessor interface, which will call the postProcessBeforeInitialization(Object obj, String s) method.

(5)InitializingBean 与 init-method:

If the bean is configured with the init-method attribute in the Spring configuration file, its configured initialization method will be automatically invoked.

(6) If the Bean implements the BeanPostProcessor interface , the postProcessAfterInitialization(Object obj, String s) method will be called; since this method is called at the end of the Bean initialization, it can be applied to memory or caching technology;

After the above steps are completed, the Bean has been created correctly, and then the Bean can be used.

(7) DisposableBean :

When the Bean is no longer needed, it will go through the cleaning phase. If the Bean implements the DisposableBean interface, it will call its implemented destroy() method;

(8)destroy-method:

Finally, if the destroy-method attribute is configured in the Spring configuration of this Bean, its configured destruction method will be automatically invoked.

8. The realization principle of Spring AOP?

​ The dynamic proxy used by Spring AOP. The so-called dynamic proxy means that the AOP framework does not modify the bytecode, but temporarily generates an AOP object for the method in memory. This AOP object contains all the methods of the target object, and The specific pointcut is enhanced, and the method of the original object is called back.

​ There are two main ways of dynamic proxy in Spring AOP, JDK dynamic proxy and CGLIB dynamic proxy. The JDK dynamic proxy receives the proxied class through reflection, and requires the proxied class to implement an interface. The core of JDK dynamic proxy is InvocationHandler interface and Proxy class.

​ If the target class does not implement the interface, then Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library) is a code-generated class library that can dynamically generate subclasses of a certain class at runtime. Note that CGLIB is a dynamic proxy through inheritance, so if a class is marked as final, then it cannot use CGLIB as a dynamic proxy.

9. How does Spring manage affairs?

​ Spring transaction management mainly includes three interfaces, and Spring transaction is mainly completed by three of them ( PlatformTransactionManager, TransactionDefinition, TransactionStatus ).

1. PlatformTransactionManager : Transaction Manager-mainly used for the management of platform-related transactions

There are three main methods:

  • commit transaction commit;
  • rollback transaction rollback;
  • getTransaction Get the transaction status.

2. TransactionDefinition : Transaction definition information-used to define transaction-related attributes, used by the transaction manager PlatformTransactionManager

This interface has the following four main methods:

  • getIsolationLevel: Get the isolation level;
  • getPropagationBehavior: get the propagation behavior;
  • getTimeout: Get the timeout time;
  • isReadOnly: Whether it is read-only (the attribute becomes false when saving, updating, and deleting—read and writing, and true when inquiring—read only)

The transaction manager can optimize according to this return value, and the configuration information of these transactions can be configured through the configuration file.

3. TransactionStatus : The specific operating status of the transaction-the status information of the transaction at each point in the transaction management process.

For example, its several methods:

  • hasSavepoint(): Returns whether this transaction contains a savepoint,
  • isCompleted(): Returns whether the transaction has been completed, that is, whether it has been committed or rolled back
  • isNewTransaction(): Determine whether the current transaction is a new transaction

Advantages and disadvantages of declarative transactions :

  • Advantages : There is no need to write transaction-related code in the business logic code, just configure or use annotations (@Transaction) in the configuration file, which is not intrusive.
  • Disadvantages : The most fine-grained declarative transaction acts on the method. If there is a transaction requirement like a code block, you can only work around it and turn the code block into a method.

10. What are the different transaction propagation behaviors of Spring and what are they used for?

 

11. What design patterns are used in Spring?

  • Proxy mode-is used more in AOP.
  • Singleton mode—The bean defined in the spring configuration file defaults to the singleton mode.
  • Template method-used to solve the problem of code duplication. For example. RestTemplate, JmsTemplate, JpaTemplate.
  • Factory pattern—BeanFactory is used to create instances of objects.
  • Adapter--spring aop
  • Decorator--spring data hashmapper
  • Observer-spring event-driven model
  • Callback--Spring Aware callback interface

12. How does Spring resolve circular dependencies?

https://blog.csdn.net/qq_36381855/article/details/79752689

13, the scope of the bean

(1) Singleton: By default, there is only one bean instance in each container, and the singleton mode is maintained by the BeanFactory itself.

(2) Prototype: Provide an instance for each bean request.

(3) request: Create an instance for each network request. After the request is completed, the bean will be invalidated and recycled by the garbage collector.

(4) Session: Similar to the request scope, ensure that there is an instance of a bean in each session. After the session expires, the bean will become invalid.

14. What are the different types of events in the Spring framework

(1) Context update event (ContextRefreshedEvent): It is triggered when the refresh() method in the ConfigurableApplicationContext interface is called.

(2) ContextStartedEvent: This event is triggered when the container calls the Start() method of ConfigurableApplicationContext to start/restart the container.

(3) Context stop event (ContextStoppedEvent): This event is triggered when the container calls the Stop() method of ConfigurableApplicationContext to stop the container.

(4) ContextClosedEvent: This event is triggered when the ApplicationContext is closed. When the container is closed, all singleton beans managed by it are destroyed.

(5) RequestHandledEvent: In a web application, this event is triggered when an http request (request) ends.

15. What are the types of Spring notifications

(1) Before advice: A notice executed before a join point, but this notice cannot prevent execution before the join point (unless it throws an exception).

(2) After returning advice: A notice executed after a join point is normally completed: for example, a method does not throw any exceptions and returns normally.

(3) After throwing advice: The advice executed when the method exits by throwing an exception.

(4) After (finally) advice: The notification executed when a connection point exits (regardless of whether it is a normal return or an abnormal exit).

(5) Around Advice: An advice surrounding a join point, such as a method call. This is the most powerful type of notification. Surround notifications can complete custom behaviors before and after the method is called. It also chooses whether to continue executing the connection points or directly return their own return value or throw an exception to end the execution. Surround notifications are the most commonly used type of notification.

16, Spring's automatic assembly

In spring, the object does not need to find or create other objects associated with it by itself. The container is responsible for assigning the object references that need to cooperate with each object, and uses autowire to configure the automatic loading mode.

There are 5 kinds of automatic assembly in the Spring framework xml configuration:

(1) no: The default method is not to perform automatic assembly, and the bean is assembled by manually setting the ref attribute.

(2) byName: Automatic assembly is carried out by the name of the bean. If the property of one bean is the same as the name of another bean, automatic assembly will be carried out.

(3) byType: Automatic assembly through the data type of the parameter.

(4) Constructor: Use the constructor to assemble, and the parameters of the constructor are assembled through byType.

(5) autodetect: automatic detection, if there is a construction method, it is automatically assembled by construct, otherwise it is automatically assembled by byType.

Annotation-based method:

Use the @Autowired annotation to automatically assemble the specified bean. Before using @Autowired annotation, you need to configure it in the Spring configuration file, <context:annotation-config />. When spring IoC is started, the container automatically loads an AutowiredAnnotationBeanPostProcessor post processor. When the container scans for @Autowied, @Resource, or @Inject, it will automatically find the required bean in the IoC container and assemble it to the properties of the object. When using @Autowired, first query the corresponding type of bean in the container:

If the query result is exactly one, the bean is assembled to the data specified by @Autowired;

If there is more than one result of the query, @Autowired will search by name;

If the result of the above search is empty, an exception will be thrown. When solving, use required=false.

@Autowired can be used for: constructors, member variables, Setter methods

Note: The difference between @Autowired and @Resource

(1) @Autowired is injected by type assembly by default. By default, it requires dependent objects to exist (you can set its required attribute to false).

(2) @Resource assembles injection according to the name by default. Only when no bean matching the name is found, the injection is assembled according to the type.

Guess you like

Origin blog.csdn.net/zw764987243/article/details/111313342