Simple understanding of Spring IOC and AOP and code examples

  • 2020-12-09 00:51:04
  • OfStack

Spring is an open source framework that does two things, IOC (Inversion of Control) and AOP (aspect-oriented programming).

IOC

Inversion of control, also known as dependency inversion.

The so-called dependency, from the point of view of the program, is that if A calls the method of B, then A depends on B, and A uses B anyway, then A depends on B. So-called inversion, you must understand if not upside down, will be how to wear, because A must have B, only can call B, if not upside down, which means A initiative for B instance: Bb = newB (), which is the most simple method of obtaining B instance (of course, all kinds of design patterns can help you to obtain B instance, such as factories, Locator, etc.), and then you can call b object. Therefore, not inverting means that A should actively acquire B before using B. Here, you should understand what an inversion means. Inversion means that if A wants to call B, A does not need to actively get B, but someone else will automatically send B to the door.

Inversion of control refers to the transfer of control. For example, when a person is driving, he/she should find the car by himself/herself under normal circumstances. After the implementation of inversion of control, he/she does not need to consider where the car comes from, but drives directly, and then transfers the control of finding the car to another object. Take a look at the code below

Start by defining an interface, Car


public interface Car {
  void go();
}

Define two cars


public class Benz implements Car {

  public void go() {
    System.out.println("benz go......");
  }
}

public class BMW implements Car{

  public void go() {
    System.out.println("bmw go......");
  }
}

Below is the man driving


public class Person {

  Car car=new Benz();

  void DriveCar(){
    System.out.println("begin drive");
    car.go();
  }
}

This is normal code control flow, people want to drive, you have to instantiate a car. But, in this case, the person can only drive one kind of car. So how do you get this guy to be able to drive all kinds of cars, which is to do inversion of control, in other words, instead of instantiating the car himself, how does that person get the object of the car? Inversion of control can be achieved by using dependency injection (Dependency Injection, or DI for short) to give the person the object of the car. So, we're going to modify the Person class


public class Person {

  Car car=null;
  public Person(Car car){
    this.car=car;
  }

  void driveCar(){
    System.out.println("begin drive");
    car.go();
  }
}

The Person class now does not instantiate the car object itself, but instead obtains the car object through the constructor, so it can drive any kind of car as long as the car implements the Car interface. See 1 How to use the Person class


public static void main(String[] args) {
  Person p=new Person(new Benz());
  p.driveCar();
}

Today's Person class can drive more than one car, as long as you pass it in through the constructor. In this case, the Car object is a dependency of the Person class. When we instantiate the Person class, we pass an instance of Car to the Person class, which is called dependency injection. Our Person class implements inversion of control.

What exactly does Inversion of control reverse? One saying goes like this: inversion of control is the process of acquiring object dependencies. After the inversion of control, the process of acquiring dependent objects changes from self-management to IOC container injection.

The way Spring implements dependency injection

In the above line, Person p=new Person(new Benz()); , we manually took an object of Benz() and injected it into the Person class. Spring doesn't do that because Spring feels that your line of code instantiates a specific Benz class. If you want to instantiate an BMW class here in the future, you need to change the code, right? I'll just write it down in the configuration file, even if you need to be careful in the future, at least you don't need to change the code, so here's the configuration


<beans>
  <bean id="car" class="com.XXX.Benz" />
  <bean id="person" class="com.XXX.Person" >
    <property name="car" ref="car" />
  <bean/>
</beans>

Then, Spring provides a mechanism to get the Person class object from the configuration file, the car object from which it came will be assembled, and the person object does not need to care which specific class was passed in. Therefore, Spring as an IOC framework mainly does two steps: create the relationship between objects and assemble objects.

AOP

AOP (Aspect Oriented Programming) is tangent oriented programming, and I'll give you an example of what it is. In a complete website project, many modules need to do logging, many places need to do login judgment, many places need to do exception handling. The logic of logging, logging decisions, exception handling, etc., is called a slice. If I write the logic of these facets everywhere, then the maintainability of the code can be assumed. AOP is designed to achieve separation of concerns by pulling out the logic of these aspects and writing them to separate classes, and then figuring out how to assemble them into a block of 1-like modules that don't even know they're there.

The goal of aspect-oriented programming is to separate concerns. What are the concerns? It's what you do. It's what you focus on. If you are a son elder brother, do not have what life goal, everyday be clothes come to stretch out one's hand, meal come to open one's mouth, know to play 1 thing only all day! So, every day you open your eyes and just think about eating and playing (the things you have to do), but before you play, you have to get dressed, put on your shoes, make the bed, cook, etc., etc. These things are your focus, but you just want to eat and play. So what do you do? All these things are delegated to others. Before you go to the table, there is a dedicated servant A dress for you, the servant B wear shoes for you, the servant C help you fold the quilt, servant C cooking for you, then you begin to eat, to play (this is the business you 1 day), after you finish your business, come back, then 1 series servants began to help you do this do that, then 1 day is over!

The nice thing about AOP is that you only need to do your job and others will do everything else for you. On a day when you want to run naked and don't want to get dressed, fire your servant A! One day, you may want to take some money with you before you leave, so hire a servant, D, to help you withdraw money! So that's AOP. Each person has his own role, flexible combination, to achieve a configurable, pluggable program structure.

From an Spring perspective, the biggest use of AOP is in providing transaction management capabilities. Transaction management is a concern, your business is to access the database, and you don't want to deal with transactions (too annoying), so Spring automatically opens transactions for you before you access the database, and automatically commits/rolls back transactions for you after you access the database!

Look at the code below. It doesn't matter if you don't understand


<bean id="audience" class="com.springinaction.springidol.Audience" />
<aop:config>
 <aop:aspect ref="audience">
  <aop:pointcut id="performance" expression=
    "execution(* com.springinaction.springidol.Performer.perform(..))" 
    />

  <aop:before 
    pointcut-ref="performance"
    method="takeSeats" /> <!--<co id="co_refPointcut"/>-->
  <aop:before 
    pointcut-ref="performance"
    method="turnOffCellPhones" /> <!--<co id="co_refPointcut"/>-->
  <aop:after-returning
    pointcut-ref="performance" 
    method="applaud" /> <!--<co id="co_refPointcut"/>-->
  <aop:after-throwing 
    pointcut-ref="performance" 
    method="demandRefund" /> <!--<co id="co_refPointcut"/>-->
 </aop:aspect>
</aop:config>

The above configuration roughly means that when the ES135en.perform method is about to occur, the agent in the Spring framework intercepts the target method (ES138en.perform ()), executes the Audience.takeSeats () and Audienceturn.OffCellPhones () methods before executing the target method, then runs the target method, and then runs the Audienceturn.applaud () method when the target method has finished executing. If the target method unfortunately throws an exception, the agent runs the Audienceturn.demandRefund () method. In summary, Spring's proxy class monitors the execution of target methods in all directions, and the target methods are so focused on their own business that they don't even know that the proxy class exists.

conclusion

That's the end of this article on a simple understanding of Spring's IOC and AOP, as well as code examples, and I hope you found it helpful. Those who are interested can continue to see this site:

Spring Ioc simulation implementation details

Spring AOP interception -3 ways to implement automatic agent detail

If there is any deficiency, please let me know. Thank you for your support!


Related articles: