Three. Spring

How many modules are there in Spring Framework and what are they?

Insert picture description here

spring core container: Core Container

  1. Spring Core
  2. Spring Bean
核心容器提供spring的基本功能。
核心容器的主要组件是BeanFactory,它是工厂模式的实现。
BeanFactory使用控制反转(IOC)模式将应用程序的配置
和依赖性规范与实际的应用程序代码分开
  1. Spring Context
spring上下文是一个配置文件,向spring框架提供上下文信息。
spring上下文包括企业服务。
例如:JNDI\EJB\电子邮件、国际化、事件机制、校验和调度功能
  1. Spring Games
全称为spring expression language,缩写为spel。
能够在运行时构建复杂表达式、存取对象图属性、对象方法调用等。
可以用来配置bean的定义

Data Access:
This layer of Data Access provides support for interacting with the database. It contains the following modules:

  1. JDBC
  2. SNAKE
  3. OXM
用于将java对象和xml文件进行映射
  1. Transction
事务管理:声明式事务和编程式事务

WEB

  1. WebMVC
MVC是一个全功能构建web应用程序的mvc实现。
通过策略接口,mvc框架变成高高度配置的,容纳了大量视图技术,其中包括JSP、Itext和POI
  1. WebFlux
  2. WebSocket
提供一个在web应用中实现高效、双向通讯,需考虑客户端和服务端之间高频和低延迟时信息交互的机制
一般的应用场景有:在线交易、网页聊天、游戏、协作、数据可视化等

AOP
through the configuration management feature, the spring aop module directly integrates the aspect-oriented programming function into the spring framework. Therefore, it is easy to make any object managed by the spring framework support the aop
spring aop module to provide transaction management services for objects in spring-based applications. By using spring aop, you can integrate declarative transaction management into your application without relying on EJB components.

Aspects

Instrumentation
This layer provides support for class detection and class loader implementation

other

  1. JMS
  2. Test
使用JUnit和TestNG进行测试支持
  1. Messaging
该模块为STOMP提供支持,支持注解编程模型

What are the benefits of using the Spring framework?

advantage

  1. DI: Make the dependencies between the constructor and Javabeans and properties files clear at a glance
  2. Lightweight: Compared with EJB containers, IoC containers tend to be more lightweight. As a result, IoC container has limited memory and CPU resources, and it becomes very advantageous to develop and publish applications.
  3. Aspect-oriented programming (AOP): Support aspect programming, which can separate the business logic of the application from the service of the system at the same time
  4. Integrate mainstream frameworks: such as ORM framework, Logging framework, Quartz and JDK Timer, and other view technologies
  5. Modularity: Named after packages and classes to make it easier to see which modules belong to
  6. Convenient testing: provide test classes for development testing
  7. Web framework
  8. Transaction management: provides a convenient transaction management interface
  9. Exception handling

Disadvantage

  1. Each framework has problems, and the adjustment phase is not intuitive, and the problem is not determined by the container. It takes time to understand
  2. Many implementations are encapsulated. To meet the needs of rapid development colleagues, the implementation is hidden. As a result, many engineers do not know how to work after leaving spring.

What design patterns are used in the Spring framework?

  1. Proxy mode: more used in aop and remoting
  2. Singleton mode: The bean defined by spring configuration file defaults to singleton mode
  3. Template method: used to solve the problem of code duplication. Such as RestTemplate, JdbcTemplate
  4. Front controller: DispatcherServlet is provided to distribute requests
  5. Factory pattern: BeanFactory is used to create instances of objects

What is the Spring IoC container?

The core of spring is the Spring IoC container. The container creates Bean objects, assembles them together, configures them and manages their complete life cycle

  1. The spring container uses dependency injection to manage the bean objects of the application
  2. The container accepts instructions for instantiation, configuration and assembly of objects by reading the provided configuration metadata Bean Definition
  3. The configuration metadata can be provided through XML, java annotation or java config code

What is dependency injection?

In dependency injection, you do not have to actively or manually create objects, but you must describe how to create them

What is the difference between IoC and DI?

IoC is a broader concept, DI is more specific.
It is an idea of ​​separating the caller from the callee.

How many ways can be used to complete dependency injection?

  1. Interface injection
  2. Constructor injection
  3. setter injection (used more)

How many types of IoC containers are there in Spring?

BeanFactory : The top-level design layer, like a factory class containing a collection of Beans. It will request instantiation of the Bean object on the client

ApplicationContext : the user interface layer, inherits the BeanFactory interface, and provides some additional functions on top of it

  1. MessageSource: manage messages, realize internationalization and other functions
  2. ApplicationEventPublisher: Event publishing
  3. ResourcePatternResolver: Multi-resource loading
  4. EnvironmentCapable: Related to environment variables in the system
  5. Lifecycle: Manage life cycle
  6. Closable: close, release resources
  7. InitializingBean: custom initialization
  8. BeanNameAware: Set the Aware interface of beanName

applicationContext will automatically initialize non-lazy loaded Bean objects

Difference between the two

BeanFacotry ApplicationContext
Lazy loading Even load
Syntax display provides resource object Create and manage resource objects yourself
Does not support internationalization Support internationalization
Does not support dependency-based annotations Support dependency-based annotation
Low-level container Advanced container

Commonly used BeanFactory container

XmlBeanFactory: Create a response bean based on the content defined in the xml file

Commonly used ApplicationContext container?

  1. ClassPathXmlAplicationContext: Read the context from the xml configuration file of the classpath and generate the context definition:
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
  1. FileSystemXmlApplicationContext: Read the context from the xml configuration file in the file system:
  2. XmlWebApplicationContext: read the context from the xml file of the web application
  3. ConfigServletWebServerApplicationContext: spring boot implementation to obtain context

Benefits of IoC

  1. Minimize the amount of code in the application
  2. Loosely coupled with minimal impact and minimal intrusive mechanism
  3. Support instant instantiation and lazy loading of bean objects
  4. Easy to test

How is IoC implemented?

Simply put, it is the realization of factory mode + reflection mechanism

What is Spring Bean

  1. Bean is instantiated, configured, assembled and managed by the Spring IoC container
  2. Bean is created based on the configuration metadata BeanDefinition provided by the user to the IoC container

What configuration methods does Spring have?

  1. xml configuration file
  2. Annotation configuration
  3. Java Config configuration

Does Spring support centralized Bean Scope?

  1. singleton: Each spring IoC container has only one single Bean instance. default allocation
  2. Prototype: Each request will generate a new instance
  3. Request: Each Http request will generate a new Bean instance, and the instance is only valid in the current Http request
  4. Session: Each session will generate a new Bean instance, and the Bean is only valid in the current Http session
  5. Application: Each Web Application will generate a new Bean, and the Bean is only valid in the current Web Application

The life cycle of Spring Bean in the container?

The initialization process of spring bean is as follows:

  1. Instantiate the Bean object
    spring container according to the Bean Definition in the configuration to instantiate the Bean object
    spring uses dependency injection to fill all attributes
Bean Definition 可以通过 XML、java注解或java config代码提供
  1. Aware related attributes, injected into the Bean object
    2.1 If the Bean implements the BeanNameAware interface, the factory calls the setBBeanName(String name) method by passing the BeanName of the
    Bean 2.2 If the Bean implements the BeanFactoryAware interface, the factory passes its own instance to call setBeanFactory(BeanFactory beanFactory ) Method
  2. Call the corresponding method to further initialize the Bean object
    3.1 If there is any BeanPostProcessor associated with the Bean, call the preProcessBeforeInitialization(Object bean, String beanName) method
    3.2 If the Bean implements the InitializingBean interface, then call the afterPropertiesSet() method
    3.3 If specified for the Bean Init method, then this method will be called

Destruction process of Spring Bean

  1. If the Bean implements the DisposableBean interface, when the spring container is closed, the destroy() method will be called
  2. If you specify the destroy method for the Bean, it will be called
    Insert picture description here

What are spring internal beans?

The bean can only be declared as an inner bean when the bean is only used as the attribute of another bean

  1. Spring provides xml-based configuration metadata provided in
  2. Inner beans are always anonymous, and they are always used as prototypes

What is spring assembly?

When the beans are combined together in the spring container, it is called assembly or bean assembly. The spring container needs to know what beans are needed and how the container should use injection to bind the beans together and assemble the beans.

What are the methods of automatic assembly?

The spring container can automatically assemble beans, which means that spring can automatically resolve bean collaborators by checking the content of beanFactory. Different modes of automatic assembly:

  1. no: default configuration, no automatic assembly, use display Bean reference for assembly
  2. byName: Inject object dependencies based on the name of the bean. It matches and assembles the bean whose properties are defined by the same name in the xml file
  3. byType (commonly used): Inject object dependencies according to the type, if the type of the attribute matches a Bean type in the xml file, it will match
  4. Constructor: Inject dependencies by calling the constructor of the class, which has a large number of parameters
  5. autodetect: first try to assemble through the constructor autowire, if not, try to assemble automatically through byType

Lazy loading

By default, all beans with a singleton scope will be created after the container is started, but some scenarios do not need to be created in advance. This is the bean can set lzay-init = "true", and it will not be created when the container starts. , Will be created when the bean needs to be obtained

Are singleton beans in the spring framework thread-safe?

  1. Need to be solved by the developer
  2. Whether a singleton bean is thread-safe is not a key concern of Spring. Spring only needs to provide the function of creating singleton beans and multiple beans based on configuration.
  3. Most spring beans have no mutable state, so they are
    thread-safe to a certain extent
  4. If there are multiple states, the simplest solution is to change the role of the bean to prototype

How does spring bean solve the circular dependency problem?

Three-level cache For
example, there is such a dependency: A->B->C->A

  1. First, A completes the first step of initialization and exposes himself through ObjectFactory in advance. During initialization, he finds that he depends on object B. At this time, he will try to get(B). At this time, B is not created.
  2. Then B went to the initial stage, and found that he relied on C, and C was not created either
  3. At this time, C starts to initialize again, but found that it depends on A during the initialization process, so try to get (A). At this time, because A has been added to the cache (usually added to the third-level cache singletonFactories), it is advanced through ObjectFactory Exposure, so you can get A through the ObjectFactory#getObject() method. After C gets the A object, it initializes smoothly, and then adds itself to the first level cache
  4. B can also get the C object to complete the initialization, and A can also get the B object to complete the initialization. At this time, the entire link has been initialized.

What is AOP?

Aspect-oriented programming

What is Aspect?

Composed of PointCut and Advice

  1. It includes both the definition of crosscutting logic and the definition of connection points
  2. Spring aop is the framework responsible for implementing the aspect. It compiles the crosscutting logic defined by the aspect to the connection point specified by the aspect.
    The focus of AOP's work is how to enhance the connection points of the weaving target object. There are two tasks here:
  3. If you locate to a specific JoinPoint through PointCut and Advice
  4. How to write aspect code in Advice

What is JoinPoint?

Cut point, some time points in program operation:

  1. Execution of a method
  2. An exception handling

What is PointCut?

Match the conditions of JoinPoint.

  1. Advice is associated with a specific PointCut and executed in the JoinPoint that matches the PointCut. Both Advice=>PointCut=>JoinPoint
  2. In spring, all methods can be considered JoinPoint, but we do not need to add Advice to all methods. The role of PointCut is to provide a set of rules to match JoinPoint, and add Advice to JointPoints that meet the rules.

What is the difference between JoinPoint and PointCut?

  1. All execution methods in spring aop are joinPoint, and PointCut is just a description information, used to match JoinPoint, and weave the matched into Advice
  2. Advice is executed on JoinPoint, and PointCut specifies which JointPoint can execute which Advice

What is Advice?

  1. The action taken by the Aspect at a specific JointPoint is called Advice
  2. Spring AOP uses Advice as an interceptor and maintains a series of interceptors around JpinPoint

What types of advice are there

  1. Before
  2. After Returning
  3. After Throwing
  4. After Finally
  5. Around

What is a transaction?

A transaction is a unified commit or rollback operation for a series of database operations. If the insertion is successful, either succeed or fail together

What are the characteristics of transactions?

ACID:

  1. Atomicity: All operations in a transaction either all succeed or all fail.
  2. Consistency: Before and after the transaction, the integrity of the cry of verse has not been destroyed.
  3. Isolation: Allow multiple concurrent transactions to read and modify it at the same time. Isolation can prevent transaction inconsistency caused by cross execution when multiple transactions are executed concurrently. Transaction isolation level: read uncommitted, read committed, repeatable read and serialization
  4. Persistence: the transaction ends, the database is permanently dropped, and the disk backup is saved

What types of transactions does spring support?

  1. Declarative transaction: through annotation or xml-based configuration transaction, transaction management and business code separation
  2. Programmatic transaction: Transaction management is realized by coding, and the acquisition, submission, and rollback of the calling transaction that need to be displayed in the code

How does spring transaction integrate with different data persistence layer frameworks?

Spring has a PlatformTransactionmanager interface class with only 3 methods

  1. getTransaction()
  2. commit()
  3. rollback

All persistence layer frameworks will implement this interface of spring

Guess you like

Origin blog.csdn.net/qq_37629227/article/details/112799004