My inversion of control, dependency injection, and the understanding of tangent-oriented programming

Source: Internet
Author: User
Tags abstract abstract definition aop extend finally block object model throwable jboss
Thank http://blog.xiaohansong.com/2015/10/21/IoC-and-DI/for the map
1. What is control. As shown in the following figure, we see the object in the software system high coupling phenomenon. The rotation of all gears is controlled by an object., such as Class B.

2. What is control reversal. is used to object to decoupleDecoupling between objects that have dependencies with third-party implementations. This third party is the IOC container. Once the IOC container has been introduced, there is no dependency between objects A, B, C, Dthe control of all gear rotation is given to the container. At this time the gear rotation control does not belong to any object, but belongs to the IOC container, so control inversion, from an object to the IOC container.

3. What is dependency injection. 3.1 What is dependency. Dependency means a relationship, if an instance of Class B is created in Class A, we say Class A relies on Class B. 3.2 See a Litchi:
public class class a{
b b;
Public A () {
b = new B ();
}
void Func () {
b.func ();
}
}
problems that occur (problems):Question 1: If you want to change the class B generation, if you need to initialize B with new B (String name), you need to modify the source code in class A; Question 2: It is difficult to test the effect of a different B object on a, because the initialization of B is written dead in the constructor of A; Question 3: If you want to When debugging an instance of Class B, it is necessary to test the instance of Class B in Class A, which increases the difficulty and complexity of the test, because when a problem occurs, it is not known whether it is the problem of Class A or class B; Workaround:
public class class a{
b b;
Public A (b b) {
this.b = b;
}
void Func () {
b.func ();
}
}
3.3) Dependency Injection definition:The B object instance is passed in as a constructor parameter of Class A, and the Class B instance has been initialized before invoking the Class A constructor. like this kind of non-self-initiated dependency, and by external incoming dependent objects, we are called Dependency injection
4. Dependency reversal 4.1 Based on the definition of dependency injection:The object of the dependency is not the active initialization of the dependent, but by the way of the external incoming by the dependent person, then the object type of the dependency can be itself, can also make it implement class or inherit subclass; 4.2 So,After analysis, the object type of the dependent person is not the dependent person can decide, (of course, the traditional method of programming is determined by the relying person), but by the external creator, so the decision of the dependent type is reversed.。 For SPIRNG, it is determined by the spring container;
4.3 dependency reversal definition:The object type of the dependent person is not determined by the relying person itself, but is determined by the external creator, what type of object the external incoming objects are, what type of object the dependent person knows nothing about;
======================================================================================= "AOP"Transferred from: http://docs.jboss.org/aop/1.0/aspect-framework/userguide/en/html/what.html "1" What's it? Face-slicing programming. 1) Slice definition:A facet is usually a scattering in a method, class, object hierarchy, or even an entire object model. Common features。 It is similar in appearance to odor behavior, it should have structure, but you cannot use code to represent this structure in traditional object-oriented techniques. 2) slices Litchi:For example, measurement (time, which measures how long it takes to run a piece of code) is a common facet. To generate useful logs from your application, you must (and usually freely) scatter informational messages in your code. However, metrics are something that your class or object model really shouldn't pay attention to. After all, metrics are not relevant to your actual application: It does not represent a customer or account, and does not implement business rules. It's just orthogonal. 3) crosscutting concern definition:In AOP, features such as metrics are called crosscutting concernsBecause it is a behavior that is "truncating" multiple points in the object model but still distinct. as a development approach, AOP recommends that you abstract and encapsulate crosscutting concerns. 4) Cross-cutting concerns Litchi:For example, suppose you want to add code to your application to measure the time that is required to invoke a particular method. In pure Java, the code looks like this.
public class Bankaccountdao {public
  void withdraw (double amount)  {
    Long startTime = System.currenttimemillis ();
    try {
      //Actual method body ...
    }
    Finally {
      long endTime = System.currenttimemillis ()-startTime;
      System.out.println ("Withdraw took:" + EndTime);}}}
Code Analysis) Although this piece of code works, there are some problems with this approach: Turning indicators on and off is very difficult, because you must manually add the code in the Try>/finally block to each method or constructor that you want to base. The parsing code really does not belong to your application code. It makes your code swell and harder to read because you have to include time in a try/finally block. If you want to extend this functionality to include methods or failure counts, or even register these statistics to a more complex reporting mechanism, you must modify many different files again. This measure is difficult to maintain, extend, and extend because it is scattered throughout the code base. This is only a small example. In many cases, OOP may not always be the best way to add metrics to a class. aspect-oriented programming provides a way to encapsulate this type of behavioral functionality. It allows you to add behaviors, such as measuring "around" your code. For example, AOP gives you programmatic control to specify that you want to call Bankaccountdao to perform metrics before executing the actual body of the code.
"2" creates facets in JBoss tangent programming 1) In a nutshell, all AOP frameworks define two things:A way to implement crosscutting concerns, as well as a programming language or a set of tags- to specify how these code snippets are applied. (One is a way to define crosscutting concerns, and the other is to specify where the crosscutting concerns are used.) 2) Let's look at JBoss AOP, its crosscutting concerns, and how to implement a metric in JBoss. The first step in creating metrics in JBoss AOP is to encapsulate the metric attributes in your own Java class. Listing two extracts the try/finally block from the Bankaccountdao.withdraw () method of the list one to metrics, which is an implementation of the JBoss AOP Interceptor class. Listing II: Implementing Metrics in the JBoss AOP interceptor
public class Metrics implements Org.jboss.aop.Interceptor
.   Public Object invoke (invocation invocation) throws Throwable {
.     Long startTime = System.currenttimemillis ();
.     try {
.       return Invocation.invokenext ();
.     finally {
.       Long endTime = System.currenttimemillis ()-startTime;       Java.lang.reflect.Method m = ((methodinvocation) invocation). Method;       System.out.println ("method" + m.tostring () + "time:" + endTime + "MS");
.   }
17.}
analysis of the above code:Under JBoss AOP, the Metrics class wraps withdraw (): When the calling code calls withdraw (), the AOP framework decomposes the method invocation into its parts and encapsulates the parts into a calling object. The framework call is then placed in any aspect between the calling code and the actual method body. When the AOP framework parses a method call, it calls metric's Invoke method on line 3rd. The 8th line wraps and delegates to the actual method and uses a closed try/finally block to perform the timing. Line 13th obtains contextual information about the method invocation from the calling object, while line 14th shows the method name and the calculated measure. Putting the measure code in its own object allows us to easily extend and capture additional measurements later. Now, the metric is encapsulated in one aspect, so let's see how to apply it. Application of "3" in JBoss AOPTo apply an aspect, you define when to execute the facet code. These execution points are called pointcuts. A pointcut is similar to a regular expression. When a regular expression matches a string, the Pointcut expression matches the event/point in the application. For example, a valid pointcut definition would be "for all calls to the JDBC Method ExecuteQuery (), invoke the facet that validates the SQL syntax."
My Summary (AOP) 1) Abstract definition of facets:Facets are common features scattered in methods, classes, object hierarchies, or the entire object model; (a set of features) 2) slices Litchi:If we want to count the execution time of a method, the code is as follows:
public class Bankaccountdao {public
  void withdraw (double amount)  {
    Long startTime = System.currenttimemillis ();
    try {
      //Actual method body ...
    }
    Finally {
      long endTime = System.currenttimemillis ()-startTime;
      System.out.println ("Withdraw took:" + EndTime);}}}
among them are the characteristics of the statistical time, and their generality is because to statistical time and add to the method of the code block, so that these blocks of code to form a slice; 3) There is a problem with the above code block issue 1) Low code reuse rate:You must manually add the slice code to the method that you want to count the execution time of the method; Issue 2) code bloat and readability is low:Timing codes really don't need you to care, these tangent lines will only make your code more expansive and difficult to read because you have to include time in a try/finally block, but this time has nothing to do with the execution of our method; Issue 3) is not conducive to code expansion (high code coupling):If you want to extend this functionality to include methods or failure counts, or even register these statistics to a more complex reporting mechanism, you must modify many different files again; the last of the last:This method of time measurement is difficult to maintain, extend and extend, because it is scattered throughout the code base; 4) What does AOP do? 4.1) Intro:Aspect-oriented programming provides a way to encapsulate the behavior of facets. AOP provides programmatic control to specify that you want to called before the actual principal of the code is executedTime statistics method to perform the execution time measurement. 4.2) All of the AOP frameworks define two things:A way to implement crosscutting concerns, as well as a programming language or a set of labels-to specify how these snippets are applied. (one is a way to define crosscutting concerns, and the other is to specify when and where to use the crosscutting concerns.)
5) How to define the approach to crosscutting concerns in AOP and where to specify the crosscutting concerns 5.1) Define crosscutting concerns:Encapsulate the Facet code metric attribute in your own Java class
public class Metrics implements Org.jboss.aop.Interceptor public
   Object invoke (invocation invocation) throws Throwable {
     Long startTime = System.currenttimemillis ();
     try {
       return invocation.invokenext ();//Call the real entity method
     }
     finally {
       long endTime = System.currenttimemillis ()-StartTime;
       Java.lang.reflect.Method m = ((methodinvocation) invocation). Method;
       System.out.println ("Method" + m.tostring () + "time:" + endTime + "MS");}}}
 
5.2) When and where the crosscutting concerns are used. to apply a slice, you define when to execute the tangent code. These execution points are called pointcuts. the pointcut is similar to a regular expression. when a regular expression matches a string, the Pointcut expression matches the event/point in the application. See the definition of a pointcut: @Before ("Execution" (* * concert. Performance.perform (..)) ")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.