What is # Aop
Compared with OOP, aspect oriented, traditional OOP code logic of the development is top-down, the process will produce some crosscutting sex problem, the problem of crosscutting and we have much relationship with the main business logic, the crosscutting sexual problems will not affect the main logic, but will be scattered to the various parts of the code, it is difficult to maintain. AOP is to deal with some crosscutting problems, AOP programming idea is to separate these problems and the main business logic, to achieve the purpose of decoupling with the main business logic. Make your code more reusable and efficient.
# AOP application scenarios
-
logging
-
Permission to verify
-
The efficiency of inspection
-
Transaction management
-
exception
# the underlying technology of springAop
# relationship between springAop and AspectJ
Aop is a concept
Both springAop and AspectJ are implementations of Aop. SpringAop has its own syntax, but the syntax is complex, so springAop uses AspectJ’s annotations, but the underlying implementation is its own
Spring AOP provides two programming styles @AspectJ support ------------> Utilizing AspectJ's annotations schema-based AOP support -----------> XML AOP :config namespace Proof: Spring, through source code analysis, we can know that the underlying use of Spring is JDK or CGLIB to complete the proxy, and on the official website Spring gives aspectJ documentation, and Spring AOP is differentCopy the code
# Spring Aop concept
Pointcut: a collection of join points -------------------> table The PointCut expression determines the number of joinPoints. The PointCut expression determines the number of joinPoints in the JoinPoint object ----------------> record. JoinPoint is a way to focus and enhance, Lesson 2: Weaving the method of attaching Proxy logic to a target object is called Weaving target object original object AOP Proxy the object that contains the code of the original object and the added code Advice Type: Before the join point is executed, but cannot prevent the normal execution of the join point unless the section execution throws an exception. After the normal execution of the join point, the normal execution during execution returns exit. Throwing an exception when After (finally) executes Around advice whether the join point exits normally or exceptionally: executes Around the join point, such as a method call. This is the most useful way to slice. Around advice can perform custom behavior before and after method calls. It is also responsible for choosing whether to continue adding points or to quickly suggest method execution by returning its own return value or throwing an exception. Proceedingjoinpoint > Proceedingjoinpoint > Proceedingjoinpoint > Proceedingjoinpoint > Proceedingjoinpoint > Proceed (), which is the method that the AOP proxy chain executes. The PROCEED () method is extended to continue the join point. JoinPoint can only obtain related parameters, but cannot execute join points. Java.lang.Object[] getArgs() : get JoinPoint method run time entry list; 2.Signature getSignature() : obtain the method Signature object of the join point; Java.lang.object getTarget() : Get the target Object where the join point is; Java.lang.object getThis() : Gets the proxy Object itself; Proceed () is overloaded, and contains any arguments. You can change the argument of any target method, as follows: @ Aspect (" perthis (this (com. Chenss. Dao. IndexDaoImpl)) ") requirements: 1. The AspectJ injection type of the object as the prototype 2. The target object must also be prototype for this reason: only if the target object is in prototype mode will the getBean get a different object each time, thus generating a new aspect object for each object, resulting in a different aspect result.Copy the code
# springAop support for AspectJ
######1. Enable @aspectJ support
Enable @AspectJ support using Java Configuration
To enable @AspectJ support with Java @Configuration, add the @enableAspectJAutoProxy annotation
@EnableAspectJAutoProxy
public class AppConfig {
}
Copy the code
Enable @AspectJ support with XML configuration
To enable @AspectJ support with an XML-based configuration, use the AOP: AspectJ-AutoProxy element
<aop:aspectj-autoproxy/>
Copy the code
####2. Declare an Aspect
Declare an @aspect annotation class and define it as a bean to be managed by Spring.
@Component
@Aspect
public class UserAspect {
}
Copy the code
#####3. Declare a pointCut
Pointcut expressions are represented by the @pointcut annotation. The pointcut declaration consists of two parts: a signature that contains the name and any parameters, and a pointcut expression that determines which method execution we are interested in.
@Pointcut("execution(* transfer(..) )"// Pointcut expression private voidanyOldTransfer() {}// Pointcut signatureCopy the code
Pointcuts determine the join points of interest, allowing us to control when notifications are executed. Spring AOP only supports join points for method execution on Spring beans, so you can think of pointcuts as matching the execution of methods on Spring beans.
/ / @component@aspect public class UserAspect {/** * declare the pointcut, Match UserDao all method calls * execution matches method execution join points * WITHIN: limits the match to join points in a specific type * args: parameters * Target: target object * this: proxy object */ @pointcut ("execution(* com.yao.dao.UserDao.*(..) )")
public void pintCut(){
System.out.println("point cut");
}
Copy the code
####4, declare an Advice notice
Advice advice is associated with pointcut pointcut expressions and runs Before, After, or Before the method matching the pointcut executes @before.
/ / @component@aspect public class UserAspect {/** * declare the pointcut, Match UserDao all method calls * execution matches method execution join points * WITHIN: limits the match to join points in a specific type * args: parameters * Target: target object * this: proxy object */ @pointcut ("execution(* com.yao.dao.UserDao.*(..) )")
public void pintCut(){
System.out.println("point cut"); } /** * declares the before notification, which is executed before the pintCut pointcut. * The notification is associated with the pointcut expression, and is run before, after, or before the method matching the pointcut is executed. * A pointcut expression can be a simple reference to a specified pointcut or a pointcut expression declared in place. */ @Before("com.yao.aop.UserAspect.pintCut()")
public void beforeAdvice(){
System.out.println("before"); }}Copy the code
# The meaning of joinPoint:
####1. execution
Used for matching methods to perform join points, a minimum-grained method used primarily in AOP.
Here the question mark indicates that the current item may or may not be present, and the semantics of the items are the following modifiers-pattern: visibility of methods such as public, protected; Ret-type-pattern: the return value type of a method, such as int, void, etc. Variable type-pattern: the full pathname of the method's class, such as com.spring.Aspect; Name-pattern: method name type, such as buisinessService(); Param-pattern: the parameter type of a method, such as java.lang.string; Throws -pattern: The type of Exception thrown by a method, such as java.lang.Exception; example: @Pointcut("execution(* com.chenss.dao.*.*(..) @pointcut ("execution(public * com.chenss.dao.*.*(..))")// Match any method of any interface and class under com.chenss.dao. ")// Match the public method @pointcut ("execution(public *) of any interface and class in the com.chenss.dao package Com.chenss.dao.*.*())")// a method that matches any interface and class in the com.chenss.dao package with no method arguments @pointcut ("execution(*) com.chenss.dao.*.*(java.lang.String, ..) // Match any interface or class in the com.chenss.dao package with a method of type String @pointcut ("execution(*) Com.chenss.dao.*.*(java.lang.string))")// Only one argument matches any interface and class in the com.chenss.dao package. @pointcut (" Execution (* com.chenss.dao.*.*(java.lang.string))")// only one argument matches any interface or class in the com.chenss.dao package. @pointcut (" Execution (public * *(..)) ")// Match any public method @pointcut ("execution(* te*(..)) // Match any method beginning with te @pointcut ("execution(* com.chenss.dao.indexDao.*(..)) IndexDao @pointcut ("execution(* com.chenss.dao.. *. * (..) ")// match any method in the com.chenss.dao package and its subpackages. For details of this expression, you can imagine and refer to the official website. It can be used as a starting point to break your fear of reading the official documentation https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#aop-pointcuts-examplesCopy the code
Since Spring has minimal granularity up to the method level, execution expressions can be used to explicitly specify method return types, class names, method names, and parameter names, and most business scenarios that require AOP in Spring only need to reach the method level. Thus the execution expression is most widely used
####2. within
// ------------ // Within is more granular than execution and can only be implemented at the package and interface and class levels. Execution can be accurate to the return value of a method, @pointcut ("within(com.chens.dao.*)")// Match any method in com.chens.dao. @pointcut (" Within (com.chens.dao.. *)")// matches any method in the com.chenss.dao package and its subpackagesCopy the code
####3. args
The ““ args expression matches methods of the specified parameter type and number, regardless of the package or class name
/ * *
-
Args differs from execution in that:
-
Args matches the type of argument passed to the method at runtime
-
Execution (* *(java.io.serializable)) matches the type of method parameters specified when the method is declared.
* /
@pointcut (“args(java.io.serializable)”)// The parameters passed at runtime are of the specified type, and the number and order of the parameters match
@pointcut (“@args(com.chens.anno.chenss)”)// Accepts a parameter and the runtime type of the passed parameter is @classified
####4. This JDK proxy refers to the interface and proxy class proxy, and cglib proxy refers to the interface and subclasses (without proxy).
####5. Target points to interfaces and subclasses/** * Note here that proxyTargetClass= is set if configuredfalse, or default tofalseJDK Proxy implementation is based on the interface implementation, Proxy class inherits Proxy, implement the interface. CGLIB inherits the proxied class. * So using target ensures that the target remains the same and the associated object is not affected by this setting. * However, when using this object, the option is set to determine whether the object can be found. */ @Pointcut("target(com.chenss.dao.IndexDaoImpl)"// The target object, that is, the proxied object. Limit the target object for the com. Chenss. Dao. The @pointcut IndexDaoImpl class ("this(com.chenss.dao.IndexDaoImpl)"Pointcut(@pointcut); // The current object, that is, the proxy object, obtains the new object by proxy object, and is not the same as the original @pointcut ("@target(com.chenss.anno.Chenss)")// Any method in the target object with @chenss @pointcut ("@within(com.chenss.anno.Chenss)")// equivalent to @targ ``` ```....... There are two important terms in proxy mode proxy Class Target Class CGLIB is different from JDK JDK is based on interface CGLIB is based on inheritance so this can work in CGLIBCopy the code
####6. @annotation
This is easy........ Effect of the method level All of these expressions are @ @ Target for instance, there is an annotation class xx, said all xx annotation class, has nothing to do with the package name) note: the above all expressions can be mixed use, | | &&! @Pointcut("@annotation(com.chenss.anno.Chenss)")// Matches methods annotated with com.chenss. Anno.ChenssCopy the code
####7 .bean
@Pointcut("bean(dao1)"// Any method @pointcut on a bean named dao1"bean(dao*)")
Copy the code
#Spring AOP XML implementation considerations:
-
Aop :config defines aspect logic to allow repetition, as many times as the logic last occurs, but as many times as it occurs
-
Aop: Aspect ID duplication does not affect normal operation and can still produce correct results
-
Aop: Overlapping pointcut ID overrides occur, whichever occurs last. Different AOP: Pointcut configurations that occur within an aspect and can be referenced to each other
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! <context:component-scan base-package="com.chenss"></context:component-scan> <! -- Defines the logical classes used by AspectJ objects that provide the logical methods to execute after the aspect --> <bean id="aspectAop" class="com.chenss.aspectj.Aspect"></bean>
<bean id="aspectAop2" class="com.chenss.aspectj.Aspect2"></bean>
<bean id="indexDao" class="com.chenss.entity.IndexDao"></bean> <! Aop: Config > <aop: Config > <aop: Config > -- AOP :aspect ID repetition does not affect normal operation, still can have the correct result --> <! -- AOP: overlapping pointcut ID will be overridden, whichever occurs last. Different AOP: pointcut configurations that occur in aspects can be referenced to each other --> < AOP :aspect ID ="aspect" ref="aspectAop">
<aop:pointcut id="aspectCut" expression="execution(* com.chenss.entity.*.*())"/>
<aop:before method="before" pointcut-ref="aspectCut"></aop:before>
fffffff
<aop:pointcut id="aspectNameCut" expression="execution(* com.chenss.entity.*.*(java.lang.String, ..) )"/>
<aop:before method="before2" pointcut-ref="aspectNameCut"></aop:before>
</aop:aspect>
</aop:config>
</beans>
Copy the code
# Spring AOP source analysis
cglib
Cglib encapsulates ASM, an open source framework, to operate bytecode and complete the creation of proxy classes
This is done by integrating the target object, then rewriting it, and then manipulating the bytecode
See ASM syntax for details
JDK
In the Proxy class, first instantiate an object ProxyClassFactory, and then call the apply method in the get method to complete the creation of the Proxy class
Two of the most important ones
GenerateProxyClass collects fields and attributes through reflection and then generates bytes
DefineClass0 Loads the above bytes internally within the JVM
Cglib is a bytecode generation proxy class that operates on subclasses by inheritance, whereas the JDK is a bytecode generation proxy class that uses Java reflection to create classes dynamically. .
# spring5 new features
Define beans using lambda expressions
2 Log Spring 4 log is using JCL, native JCL, the bottom layer through the loop to load the body of the log implementation technology, so there is a sequence, Spring 5 is using the spring-JCL, in fact, is changed by spring JCL code specific reference video about the difference between the two
There are other new features, but these two are more important, because of the time problem, other features can go to the Internet to find the corresponding information, but the two can absolutely cope with the interview, other features of the stunt, practical may not be very big.
If you want to learn more about the Spring source code, I suggest you watch this video
Spring family bucket tutorial complete set
Mainly explained the spring IOC, Spring AOP, Spring Boot bottom source code analysis