Understanding of IOC and AOP

Interview questions: 1. Talk about your understanding of IOC and AOP

References:
Try to explain the core concepts of
Spring IOC and AOP. Spring JdbcTemplate Explains
JDBC in Java in detail
[Spring Basics] AOP using annotations in practice

Answer: IOC is a container of spring, which can help us create objects without the need for us to create them manually. IOC has a powerful functional dependency injection (DI), which can better manage Beans through dependency injection to achieve the purpose of decoupling. For example: the JDBCTemplate we use can be configured in xml, and then injected and used, but we need a data source, we can switch the data source at will, so that JDBCTemplate does not force dependence on a certain data source to achieve decoupling.

Answer: AOP is often used in transactions and logs, because it can be executed without being embedded in the code.

2. I will talk about the process of IOC; there is also the pointer of B+Tree which is conducive to range search; the difference between zookeeper and eureka, one is http and the other is RPC.

3. Can the parameters of the target method be changed in Aop?

1. IOC (Design Mode: Factory Mode)

1.1. Concept: It is a spring container that helps us create objects

Two, Aop concept

Aop is a concept, springAop and aspectJ are the realization of Aop. If the front-end sends the request to the controller to the service and then to the dao from top to bottom, then springAop cuts in from the level, but it is fully decoupled from it, so as to realize some functions, such as logging, transaction, exception, and permission Wait. Realize some functions of the aspect. Such as logs, transactions, permissions, exceptions, etc.

3. The connection between Aop and aspectJ

The grammar of Aop is more complicated, so it uses the grammatical style of aspectJ, but the bottom layer is still implemented by itself.

Fourth, the use of Aop

4.1, open Aop

Enable aspectJ support through @Configuration annotation, and annotate @EnableAspectJAutoProxy.
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
    
    


}

4.2, declare an Aspect (aspect) class

Declare an Aspect annotation class, and define the class as a Bean to spring for management.

4.2.1. Aspects include notifications and entry points

@Component
@Aspect
public class AspectTest {
    
    

}

4.3. Write entry points and notifications in the aspect category

4.3.1. The entry point is which target method will be notified of execution

4.3.2. Notification is a method of execution around the target method

4.3.4. The code is as follows: (It can be found that the entry point expressions are all the same, how can I eliminate it?)

@Component
@Aspect
public class AspectTest {
    
    


    @Before("execution(* com.xuecheng.aop.service..*.*(..))")
    public void before() {
    
    
        System.out.println("before执行。。。。");
    }

    @After("execution(* com.xuecheng.aop.service..*.*(..))")
    public void after() {
    
    
        System.out.println("after执行。。。。");
    }

}

4.3.5. The optimized code is as follows:


@Component
@Aspect
public class AspectTest {
    
    
    
    @Pointcut("execution(* com.xuecheng.aop.service..*.*(..))")
    public void pointCut() {
    
    

    }


    @Before("pointCut()")
    public void before(){
    
    
        System.out.println("before执行。。。。");
    }

    @After("pointCut()")
    public void after(){
    
    
        System.out.println("after执行。。。。");
    }



}

4.4, write the target method

4.4.1, interface code

public interface FatherServ {
    
    

    public void ss();
}

4.4.2. Implementation class (target class) code

@Component("s")
public class TestService implements FatherServ {
    
    
    public void ss(){
    
    
        System.out.println("目标方法执行...");
    }
}

4.5. The test results are as follows:

before执行。。。。
目标方法执行...
after执行。。。。

Five, the entry point expression analysis in Aop

Reference: Detailed explanation of Spring AOP pointcut expression

Insert picture description here

When executing an expression, we can match the expression with the logical operators &&(and), ||(or), !(not). such as:

execution(* com.jpeony.spring.ConferenceServiceImpl.conference(..)
       && within(com.jpeony.spring.*))

An added restriction is that we only take care of the packages under com.jpeony.spring. The && here can be replaced with and,
similarly ||,! Are the same usage, flexible and changeable, and can only be handled according to the actual situation.

5.1, execution (granularity can be accurate to a specific method)

5.2, within (the granularity can only be accurate to the class)

5.2.1. Accurate to the BusinessObject class, and enhance all the methods under this class.

within(com.spring.service.BusinessObject)

5.2.2, accurate to all classes under the service package, but not including the classes under the sub-package

within(com.spring.service.*)

5.2.3, accurate to the classes under the service package and all classes of sub-packages under the package

within(com.spring.service..*)

5.3, args (granularity is the method of matching the number of parameters and the type of parameters)

5.3.1, the method of exactly matching to only one String type parameter

args(java.lang.String)

5.3.2. Exactly match until the parameter is of String type at the beginning and Integer type at the end, and any number and type of parameters can be in the middle. Here wildcards use "...", not "*"

args(java.lang.String,..,java.lang.Integer)

5.4, ​​the difference between this and target

5.4.1. When used for surround notification, when the target object is specified in this and target, if the target object does not implement an interface, the execution result is the same; if the target object implements an interface, this cannot perform the surround notification, but the target can of.

5.5、@within

5.5.1. When the granularity matches to which classes the specified annotation is placed on, which classes are enhanced.

5.6、@annotation

5.6.1. Similar to @within, @annotation acts on methods.

5.7、@args

5.7.1, indicates that when the class marked with annotations is used as a parameter, the execution method is enhanced

5.8、@DeclareParents

5.8.1. Represents the introduction of new attributes and methods for the specified target class.

5.9 、 perthis 和 target

5.9.1. In the case of multiple threads, create multiple instances of the Aspect class

Six, surround notification

6.1. The slices are as follows:

Step 1: Add annotation @Around

Step 2: Pass in the parameter ProceedingJoinPoint on the notification method, and then call its method proceed();


@Component
@Aspect
public class AspectTest {
    
    

    @Around("pointCut()")
    public void aroundTest(ProceedingJoinPoint proceedingJoinPoint) {
    
    
        try {
    
    
            System.out.println("环绕通知之前执行");
            proceedingJoinPoint.proceed();
            System.out.println("环绕通知之后执行");
        } catch (Throwable throwable) {
    
    
            System.out.println("异常通知执行。。");
        }
    }

    @Pointcut("execution(* com.xuecheng.aop.service..*.*(..))")
    public void pointCut() {
    
    

    }
}

Seven, the parameters of the target method can be obtained and modified

7.1. Pass in the parameter JoinPoint in the notification method, and call the method getArgs(); to obtain the parameters of the target method and modify it.

    @Around("execution(* com.xuecheng.aop.service..*.*(..))")
    public void aroundTest(JoinPoint JoinPoint) {
    
    
        //获取目标方法的参数,并可以对其进行修改
		// Object[] args = joinPoint.getArgs();
    }

8. Classification of Advice

8.1. The Spring aspect defines 5 types of notifications:

1) Before notification (Before): The notification function is called before the target method is called.

2) After notification (After): Call the notification after the target method is completed, and don't care what the output of the method is. (Regardless of whether the target method is successfully executed or not, the post notification must be executed.)

3) After-returning: The notification is called after the target method is successfully executed. (Executed before the post notification, the method must be executed successfully before it can be executed!)

4) Exception notification (After-throwing): Call notification after the target method throws an exception.

5) Around notification (Around): The notification wraps the notified method, and executes custom behavior before and after the notified method is called. (ProceedingJoinPoint parameter can have, but JoinPoint cannot exist.)

ProceedingJoinPoint inherits from JoinPoint; there are two methods in ProceedingJoinPoint: proceed(); and proceed(Object object);

Nine, AOP terminology

Point of contact, connection point, aspect, notification

The connection point is a collection of tangent points, and the connection point is an ethereal and large-scale concept. The aspect is the combination of notice and point. What the notice tells us is, "When?" and "What to do?"; and the point of contact tells us, "Where?"

Ten, the execution order of Aop's aspect class

10.1 The order of execution can be solved by the annotation @order(1). The lower the number, the higher the priority.

Eleven, springAop changes the parameters of the target method and the return value of the target method to be modified (only applicable to around (around notification))

You can also pass the changed parameters into the parameters of the target method for execution

    @Around("pointCut()")
    public void before(ProceedingJoinPoint joinPoint)  {
    
    
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
    
    
            System.out.println("方法的参数是"+arg);
        }

        System.out.println("环绕之前。。。");
        try {
    
    
            String proceed = (String) joinPoint.proceed();
            proceed="改变后的返回值";
            System.out.println(proceed);
        } catch (Throwable throwable) {
    
    
            throwable.printStackTrace();
        }
        System.out.println("环绕之后。。。");


    }
Test code
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class);
        TestService s = (TestService) applicationContext.getBean("s");
        s.ss("String参数。。");

    }
}
Test Results
方法的参数是String参数。。
环绕之前。。。
目标方法执行...String参数。。
改变后的返回值
环绕之后。。。

Guess you like

Origin blog.csdn.net/weixin_43983411/article/details/108125905