A brief introduction to IoC and AOP in Spring

Introduction to Spring IoC

  IoC is a container. In Spring, it will think that all Java resources are Java Beans. The goal of the container is to manage these beans and the relationship between them. Therefore, various beans loaded in Spring IoC can also be understood as various Java resources, including Java Bean creation, events, behaviors, etc., which are managed by the IoC container. In addition, there will be certain dependencies between Java Beans. For example, classes are composed of teachers and students. Assuming that teachers and students are both Java Beans, then obviously a dependency relationship is formed between the two. Teachers and students Students have a relationship between educating and being educated. These Spring IoC containers are able to manage it. It's just that Spring IoC manages objects and their dependencies. It is not artificially created actively, but is created by Spring IoC itself through description. That is to say, Spring relies on description to complete the creation of objects and their dependencies.
  For example, sockets are defined by national standards (this standard can be defined as an interface, Socket). There are two types of sockets (Socket1 and Socket2), as shown in the figure:
insert image description here
  There are two types of sockets to choose from. Which one to use? ? We can use socket 1 (Socket1) by the following code:

Socket socket = new Socket1();
user.setSocket(socket);
user.useSocket();

  After using Socket socket = new Socket1();, the national socket standard interface (Socket) is bundled with socket 1 (Socket1). This will have a disadvantage: if you want to use other sockets, you need to modify the code. In this case, the Socket interface is coupled with its implementation class Socket1. If one day Socket1 is no longer used, but Socket2 is to be used, then the code should be modified to the following code:

Socket socket = new Socket2();
user.setSocket(socket);
user.useSocket();

  If there are other better sockets, wouldn't it be necessary to modify the source code? There are thousands of objects in a large Internet. If it is to be constantly modified, it will be a great challenge to the reliability of the system. Spring IoC can solve this problem.
  First, we do not create objects in the new way, but use the configuration method, and then let the Spring IoC container find the socket through the configuration itself. First use a piece of XML to describe the socket and the user's reference socket 1:

<bean id="socket" class="Socket1"/>
<bean id="user" class="xxx.User">
	<property name="socket" ref="socket"/>
</bean>

  Note that these are not Java code, but XML configuration files, in other words just switch the configuration to:

<bean id="socket" class="Socket2"/>

  You can inject socket 2 into the user information, and it is very convenient to switch the implementation class of the socket. At this time, the Socket interface can be switched without relying on any sockets, but can be switched through configuration, as shown in the following figure: The
insert image description here
  configuration information is "I want socket 2", which is equivalent to the XML dependency configuration. At this time, Spring IoC will only get socket 2. , and then inject it into the user through the national socket standard interface, and provide it for the user to use. In other words, this is a passive behavior, and the required resources (Beans) can be obtained through the description information. The control right is in the Spring IoC container, and it will find the resources required by the user according to the description. This is the control The meaning of inversion.
  The advantage of this is that the Socket interface does not depend on a certain implementation class. When we need to use a certain implementation class, we can complete it through configuration information. In this way, if you want to modify or add other resources, you can complete it through configuration. You don't need to use the new keyword to create objects. The dependencies can also be completed through configuration, so that you can completely manage the relationship between them by plug and play.
  You don't need to look for resources, just describe the required resources to the Spring IoC container, and Spring IoC will find the resources you need. This is the concept of Spring IoC. This decouples the dependencies between beans and makes it easier to write programs with a clear structure. In addition, Spring IoC also provides management of the Java Bean life cycle, which can be delayed loading, and can define some behaviors in other life cycles, etc., to use and manage Java resources more conveniently and effectively. This is the charm of Spring IoC.

Introduction to Spring AOP

  The goal of IoC is to manage beans, and beans are the basic design of Java object-oriented (OOP), such as declaring a user class, socket class, etc. are based on object-oriented concepts.
  There are some situations that object-oriented can't handle. For example, the orders of the production department, the production department, and the financial department conform to the design concept of OOP. The order is issued, and the production department approves and prepares for payment, but the financial department finds that the price of the order is overrun and needs to cancel the order. Obviously, the overspending limit no longer affects the financial department, but also affects the approvals previously done by the production department, and they need to be abolished. We call this condition of budget overrun as aspect, which affects three OOP objects of order, production department and finance department. In reality, such an aspect condition spans 3 or more objects and affects their collaboration. Therefore, only using OOP is not perfect, and aspect-oriented programming is also required to manage the collaboration between certain objects on the aspect, as shown in the following figure: In the
insert image description here
  above figure, the solid line is the order submission process, and the dotted line is the The process of order rejection, the condition that affects them is the over-budget condition, which is a tangential condition.
  Spring AOP is often used in the programming of database transactions. In many cases, as in the above example, after the first step of database data update, we do not know whether the next step will be successful. If the next step fails, we will use the rollback function of the database transaction to Rolling back the transaction makes the database update in the first step also void. In the database transaction management implemented by Spring AOP, exceptions are used as messages. By default (which can be modified through Spring's configuration), as long as Spring receives exception information, it will roll back the database transaction to ensure data consistency. In this way, we know that in Spring's transaction management, as long as it receives exception information, it will roll back the transaction, without the need to implement this process through code. For example, in the above example, a piece of pseudocode can be used to make some necessary explanations, as follows:

/**
* Spring AOP 处理订单伪代码
* @param order 订单
**/
private void proceed(Order order) {
    
    
	// 判断生产部门是否通过订单,数据库记录订单
	boolean pflag = productionDept.idPass(order);
	if (pflag) {
    
      // 如果生产部门通过,进行财务部门审批
		if (financialDept.isOverBudget(order)) {
    
      // 财务审批是否超限
			// 抛出异常回滚事务,之前的订单操作也会被回滚
			throw new RuntimeException("预算超限!!");
		}
	}
}

  Here we see no database code at all, and no complicated try...catch...finally... statements. In reality, the same is true for Spring AOP programming. These things are shielded by Spring. You don't need to pay attention to it. You only need to pay attention to the business code. It is enough to know that if an exception occurs, Spring will roll back the transaction. Of course, this sentence is not accurate, because transactions and businesses are very complex, but Spring has provided isolation levels and propagation behaviors to control them. With Spring's encapsulation, developers can reduce a lot of code and unnecessary trouble.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326052285&siteId=291194637