Programmer’s Notes-A Quick Look at ——Spring’s Basic Concepts

  spring

(i) Spring IoC

Important concept

1. Control inversion:

Control inversion is a way to generate or obtain a specific object through description (xml or annotation in java) and through a third party.

Control inversion IoC(Inversion of Control) means that the control right of creating objects is transferred. in the past, the initiative and timing of creating objects were controlled by oneself. now, this power is transferred to a third party, such as IoC container. it is a factory specially used to create objects. it gives you whatever objects you want. with IoC container, the dependency relationship changes, and the original dependency relationship disappears. they all rely on IoC container to establish their relationship.

Control inversion is the inversion of the way in which dependent objects are acquired. Under normal circumstances, the application program actively creates the dependent objects to realize the management of the dependent objects. The control of creating the dependent objects is in the hands of the application program. The application program will actively create the object if it needs any object. This is a normal situation. After control inversion is realized, the creation and management of dependent objects are realized by the IoC container. The IoC container creates this object according to requirements. The application only passively receives and uses this object. The creation and management control of dependent objects is transferred from the application to the IoC container, which realizes control inversion.

2. Dependency Injection:

Another expression of control inversion is to allow the dependency of the calling class on the implementation class of an interface to be injected by a third party (container or collaboration class) to remove the dependency of the calling class on the implementation class of an interface.

3. Beanfacory and ApplicationContext:

Spring describes beans and their dependencies through configuration files, instantiates beans using the reflection function of Java language and establishes the dependencies between beans. Spring’s IoC container provides Bean instance caching, life cycle management, Bean instance proxy, event publishing, resource loading and other services on the basis of completing the bottom work.

Beanfacory is the core interface of Spring Framework and provides the configuration mechanism of advanced IoC. Beanfacory makes it possible to manage different java objects. ApplicationContext (application context) is based on Beanfacory and provides more reference-oriented functions. Beanfacory is the IoC container. because ApplicationContext is built on Beanfacory, we also call ApplicationContext the IoC container.

IoC container main function

1. Dynamically create and inject dependent objects.

2. Manage the life cycle of objects.

3. Mapping Dependencies.

How to implement IoC container:

1. Dependency search.

2. Dependency injection.

There are three ways to rely on injection:1. Constructor injection. 2. setter injection. 3. Interface injection.

The difference between injection and assembly:

Injection is how each parameter in a class is assigned when it is instantiated.

Assembling is to define beans and the relationships between beans.

  • Overview of assembly bean:

1. Configuration based on xml.

2. Based on the configuration in the annotation.

3. java class-based configuration.

4. based on Groovy DSL configuration.

  • Bean scope:

1. singleton: It is the default option. Spring only generates an instance of Bean for it in the whole application.

2. prototype: Spring will create a new instance for the Bean every time it is injected or when it is acquired through the Spring IoC container.

3. session: Used in web applications, Spring will only create one instance during the session.

4. request: Used in web applications, Spring will create an instance in one request, but different requests will create different instances.

Based on configuration in xml

1. Four types of automatic assembly:

(1)byName: automatically matches by name.

(2)byType: automatically matches according to type.

(3) Constructor: Automatically matches according to the constructor.

(4)autodetect: select byType or construtor according to bean’s introspection mechanism.

2. The relationship between Bean:

(1) inheritance; (2) dependence; (3) citation.

Annotation-based configuration

1. Define bean with Annotation

@Component: used to annotate all classes.

@Repository: used to annotate Dao implementation classes.

@Service: used to label the Service implementation class.

@controller: used to label the controller implementation class.

2. Automatic assembly

(1) @ autowire: Bean dependency injection through @ autowire annotation.

(2) required attribute of @ autowire: used to specify whether a matching Bean must be found.

(3)@Qualifier, specifying the name of the Bean.

Profile: Used to switch development environments.

Spring EL:

Concept: A more flexible injection method that can build complex expressions, access object properties, object method calls, etc. at runtime.

Role:

1. use bean id to refer to bean.

2. Call the method of the specified object and access the properties of the object.

3. Carry out calculation.

4. Provide regular expressions for matching.

5. Set configuration.

(2) Aspect Oriented Programming

Overview: AOP technology uses “crosscutting” technology to cut and unpack the inside of encapsulated objects and encapsulate those common behaviors that affect multiple classes into a reusable module, which is named “Aspect”, or tangent plane. The so-called “cut-planes” are simply those logic or responsibilities that have nothing to do with the business but are called together by the business modules, which are convenient to reduce the repeated codes of the system, reduce the coupling degree between the modules, and are beneficial to the operability and maintainability in the future.

AOP related concepts

1. Aspect:Modularization of a focus, this focus implementation may additionally cross-cut multiple objects. Transaction management is a good example of crosscutting concerns in J2EE applications. Aspect is implemented with Spring Advisor or Interceptor.

2. Joinpoint:A specific point during program execution, such as a method call or a specific exception, is thrown.

3. Advice:The actions performed by the AOP framework at a specific connection point. Various types of notifications include “around”, “before” and “throws” notifications. Notification types will be discussed below. Many AOP frameworks, including Spring, use interceptors as notification models to maintain an interceptor chain that “surrounds” connection points. Spring defines four advice: before advice, after advice, throw advice and DynamicIntroductionAdvice.

4. Pointcut:Specifies a collection of connection points that a notification will raise. AOP frameworks must allow developers to specify pointcuts: for example, using regular expressions. Spring defines Pointcut interface, which is used to combine MethodMatcher and ClassFilter. it can be clearly understood by name. MethodMatcher is used to check whether the method of the target class can be applied with this notification, while ClassFilter is used to check whether Pointcut should be applied to the target class.

5. Introduction:Add a method or field to the notified class. Spring allows the introduction of new interfaces to any notified object. For example, you can simplify caching by introducing an IsModified interface that enables any object. Introduction is to be used in Spring. Notifications can be implemented through delegatingProductionEnterPtor, and interfaces to be implemented by Advice and proxy classes can be configured through DefaultIntroductionAdvisor.

6. Target Object:The object that contains the connection point. Also known as notified or proxied objects. POJO。

7. aoppproxy:An object created by the AOP framework that contains notifications. In Spring, AOP proxy can be JDK dynamic proxy or CGLIB proxy.

8. Weaving:Assemble aspects to create a notified object. This can be done at compile time (for example, using the AspectJ compiler) or at run time. Spring, like other pure Java AOP frameworks, weaves in at runtime.

  • Before advice: a notice executed before a join point, but this notice cannot prevent execution before the join point (unless it throws an exception).
  • After advice: a notice executed when a connection point exits (whether it is a normal return or an abnormal exit).
  • Around Advice: a notice that surrounds a join point, such as a method call. This is the most powerful type of notification. Wrap-around notifications can complete custom behavior before and after a met hod call. It will also choose whether to continue executing connection points or directly return their own return values or throw exceptions to end execution.
  • After returning advice: A notification that is executed after a join point is normally completed. For example, a method returns normally without throwing any exceptions.
  • After throwing advice: A notification that is executed when a method throws an exception and exits.

Four ways to implement Spring AOP:

1. Implement AOP with proxyFactoryBean and the corresponding interface

2. Use XML to configure AOP

3. Use @AspectJ annotation to drive the tangent plane

4. Use AspectJ to inject slices

Multi-slice situation:

(1)aspect has an order attribute, and the number of the order attribute is the order of crosscutting concerns.

(2)Spring defaults to the definition order of aspect as the weaving order.

(3) Spring Affairs Management

1. Transaction Manager

Spring does not directly manage transactions, but provides a variety of transaction managers. They delegate the responsibility of transaction management to transactions of related platform frameworks provided by persistence mechanisms such as Hibernate or JTA. The interface of Spring Transaction Manager is ORG. Spring Framework. Transaction. PlatformTransaction Manager. Through this interface, Spring provides corresponding transaction managers for various platforms such as JDBC and Hibernate.

2. Definition of Transaction Attributes

(1) Communication behavior:

Spring defines seven propagation behaviors, the following are common types:

PROPAGATION_REQUIRED: Indicates that the current method must be running in a transaction. If the current transaction exists, the method will run in that transaction. Otherwise, a new transaction will start

PROPAGATION_SUPPORTS: Indicates that the current method does not need a transaction context, but if there is a current transaction, the method will run in this transaction

PROPAGATION_MANDATORY: indicates that the method must run in a transaction, and throws an exception if the current transaction does not exist

(2) isolation level

The isolation level defines the extent to which a transaction may be affected by other concurrent transactions.

  • ISOLATION_DEFAULT: Use the default isolation level for the backend database
  • ISOLATIONREADUNCOMMITTED: The lowest isolation level that allows reading uncommitted data changes, which may result in dirty reads, phantom reads, or nonrepeatable reads.
  • ISOLATIONREADCOMMITTED: Allows reading of data already committed by concurrent transactions, prevents dirty reads, but phantom reads or nonrepeatable reads are still possible
  • IsolationRepeatable: The results of multiple reads of the same field are consistent. Unless the data is modified by the transaction itself, dirty reads and non-repeatable reads can be prevented, but phantom reads are still possible.
  • ISOLATION_SERIALIZABLE: The highest isolation level, completely obeying ACID’s isolation level, ensures that dirty reads, nonrepeatable reads, and phantom reads are prevented, and is also the slowest transaction isolation level, because it is usually achieved by completely locking database tables related to transactions

(3) Read-only: By setting the transaction to read-only, you can give the database an opportunity to apply the optimization measures it deems appropriate.

(4) Transaction Timeout: Transaction Timeout is a timer of a transaction. If the transaction is not completed within a specific time, it will be rolled back automatically instead of waiting for it to end.

(5) Rollback Rules: These rules define which exceptions will cause transaction rollback and which will not.

3, the difference between programmatic and declarative transactions

Spring provides support for programmatic transactions and declarative transactions. Programmed transactions allow users to precisely define transaction boundaries in code, while declarative transactions (based on AOP) help users decouple operations from transaction rules.

In short, programmatic transactions intrude into business code, but provide more detailed transaction management. However, declarative transaction is based on AOP, so it can not only play the role of transaction management, but also can not affect the specific implementation of business code.

Yixin Institute of TechnologyAuthor: Yao Yuan