AOP (Face Oriented Programming) for Spring's Three Cores
Before learning the AOP of Spring's three core ideas, it is recommended that you learn:
🔴1,Srping's IOC Thought and Use
🔴2,Agent mode for underlying design mode of Spring core idea AOP
🍅 Programmer Xiao Wang's blog: Programmer Xiao Wang's Blog
🍅 Welcome 👍 Collection ⭐ Leaving a message. 📝
🍅 If there are editorial errors to contact the author, if there are good articles to share with me, I will take the essence to its dregs
🍅 The java self-study route: The java self-study route
1. What is AOP (Face Oriented Programming)?
AOP is the abbreviation of Aspect Oriented Programming, which means face-to-face programming. It is a technology to unify the maintenance of program functions through precompilation and run-time dynamic agents.
AOP (Aspect Oriented Programming) is the continuation of OOP (Object Oriented Programming), a hot spot in software development, an important content in Spring framework, and a derived paradigm of functional programming. With AOP, parts of business logic can be isolated, which reduces the coupling between parts of business logic, improves the reusability of programs, and improves the efficiency of development.
2. The Role and Advantage of AOP
Role: Enhance method functionality without modifying source code during program run
Advantages: Reduce duplicate code, improve development efficiency, and ease of maintenance
3. Underlying implementation of AOP
In fact, the bottom level of AOP is achieved through Spring's dynamic proxy technology. During runtime, Spring dynamically generates proxy objects through dynamic proxy technology, and enhances the functions of proxy object methods by intervening in their execution to invoke the methods of the target objects.
- The role of dynamic agents:
1) Add functionality without changing the source code of the target class.
Reduce code duplication
Focus on business logic code
_4) Decouple to separate your business functions from your log and non-business functions.
Agent Design Mode Detailed Notes: Detailed notes on proxy mode, to learn Spring's AOP idea, understand proxy mode first
Proxy Design Mode Notes for java Design Mode Details:
-
Agent mode is one of the structured modes
-
Problems Existing in Development
-
What is proxy mode and why it is necessary to use it
-
Static Proxy and Implementation
-
What is dynamic proxy
-
Use and differences between JDK dynamic proxy and cglib dynamic proxy
-
Comparison of Three Dynamic Agents, Advantages and disadvantages
-
Scenarios for using proxy mode
4. Concepts related to AOP
The bottom level of Spring's AOP implementation is to encapsulate the code of the dynamic proxy. After encapsulation, all we need to do is code the parts we need to focus on and configure to accomplish the enhancements of the specified target.
Before formally explaining the operation of AOP, we must understand the relevant terms of AOP, which are commonly used as follows:
1. Aspect
A facet is a proxy object = those classes to be proxied for + those extra features to be added are those
2. pointcut: Proxy objects will be generated for those classes in the future
3. Notifications/enhancements: Additional functionality to add
- Life case: jam bread to bread
Note: Aspect = pointcut + advice
4. Notification in AOP (Face Oriented Programming)
Pre-notification: Additional functionality before target method MethodBeforeAdvice
Wrap-around notification: It's a way the spring framework provides us with a way to manually control when enhancement methods are executed in code, MethodInterceptor [ ɪ nt əˈ S ɛ pt ə] Interceptor)
Post Notification: Additional functionality after the target method AfterReturningAdvice (returning[r] ɪˈ t ɜː rn ɪŋ])
Exception Notification: Perform additional functionality for exceptions ThrowsAdvice
Final notification: extra functionality that must be performed
5. Target: Target object of the proxy
6. Agent (Proxy[ ˈ pr ɑː ksi]: When a class is enhanced by AOP injection, a result proxy class is produced
7. Join Point: Join points are those points that are intercepted. In spring, these points refer to methods (additional functionality), because spring only supports connection points of method type
5. Procedures for facet programming
1. Five Notification Classes
AOP Aspect = Start Point + Notification
-
Pre-notification: MethodBeforeAdvice
-
Post Notification: AfterReturnAdvice
-
Surround notification: MethodInterceptor
-
Exception notification: ThrowsAdvice(throw [throw] θ ro ʊ z])
-
Final Notification
- Configuration syntax for notifications:
<aop : Notification Type method="Method Name in Face Class" pointcut="Tangent expression"> </aop:Notification Type>
- Extraction of tangent expression
When multiple enhanced tangent expressions are identical, the expression can be extracted, and the extracted tangent expression can be referenced in the enhancement using the pointcut-ref attribute instead of the pointcut attribute.
<aop:config> <!--Quote myAspect Of Bean For tangent objects--> <aop:aspect ref="myAspect"> <aop:pointcut id="myPointcut" expression="execution(* com.tjcu.aop.*.*(..))"/> <aop:before method="before" pointcut-ref="myPointcut"></aop:before> </aop:aspect> </aop:config>
- Configuration of aop weaving
<aop:config> <aop:aspect ref="Face class"> <aop:before method="Notification Method Name" pointcut="Tangent expression"></aop:before> </aop:aspect> </aop:config>
- Writing of the tangent expression:
execution([Modifier] Return value type package name.Class name.Method Name(parameter))
2. Steps to develop AOP
1. Development Target Class
2. Develop notification classes to determine additional functionality
3. Management Notification Class
4. Configure entry points to determine which classes to add additional functionality to
5. Delegate object creation rights to spring for target and tangent classes
6. Assembly Cut-in Point + Notification (Extra Function)
3. Dependencies needed for AOP programming
Introducing dependencies spring-aop spring-expression spring-aspects
6. Case Study of AOP Implementation Pre-Notification
1. Target Interface Class
public interface CityService { public void login(); public void add(String name); }
2. Goal Achievement Class (Core Functions)
/** * @author Wang Hengjie * @Description:Target object */ public class CityServiceImpl implements CityService{ @Override public void login() { //Pre-notification: System.out.println("Hip-Hop"); //Execute core business logic call Dao System.out.println("Logon Call Dao"); } @Override public void add(String name) { //Pre-notification: System.out.println("Hip-Hop"); //Execute core business logic call Dao System.out.println("Add Call Dao"); } }
3. Pre-notification (extra functionality) dynamic proxy code
/** * @author Wang Hengjie * @Description: Notification class. Additional features */ public class MyBeforeAdvice implements MethodBeforeAdvice { /** * Writing methods for additional functions * Parameter 1: Method currently invoked by the proxy object * Parameter 2: Parameters of the method invoked by the current proxy object * Parameter 3: Target object (proxied object) * @param method * @param objects * @param o * @throws Throwable */ @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println("Hip-Hip-Hop"); } }
4. Delegate object creation rights to spring for target and tangent classes
<!--Manage Target Objects--> <bean class="before.CityServiceImpl" id="cityService"></bean> <!--Manage Notification Class Dynamic Proxy Implementation AOP--> <bean id="myBeforeAdvice" class="before.MyBeforeAdvice"></bean>
5. Configure weaving relationships in spring.xml (pre-functionality)
<!--Assembly Cut--> <aop:config> <!--Configure entry points id:Unique identification of entry point expression:Cut-in point expressions to add extra functionality to those classes execution() A way of expressing entry points precisely to add extra functionality *: Wildcard Spaces: before.CityServiceImpl.*: All methods (..): All parameters --> <aop:pointcut id="pc1" expression="execution(* before.CityServiceImpl.*(..))"/> <!--Assembly Cut=breakthrough point+notice advice-ref:Notified id pointcut-ref:Starting Point id --> <aop:advisor advice-ref="myBeforeAdvice" pointcut-ref="pc1"></aop:advisor> </aop:config>
6. Test Code
@Test public void testMethodBeforeAdvice() { //Start Factory ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("before/spring.xml"); //Get Component Target Object Is Proxy Object CityService cityService = (CityService) ctx.getBean("cityService"); //The target object is the proxy object class com.sun.proxy.$Proxy4 System.out.println(cityService.getClass()); //Call method, call target class through proxy class cityService.add("123"); }
Note: When getting components, the target object is the proxy object
7. Circumferential Notification Cases in Spring
1. dao Layer Interface
public interface StudentDao { /** * Sign in * @param name */ public void login(String name); /** * paging * @param name * @return */ public String pageShow(String name); }
2. dao Layer Implementation Class
public class StudentDaoImpl implements StudentDao{ @Override public void login(String name) { //10,000 cycles for (int i = 0; i < 10000; i++) { } System.out.println("Database implementation login"); } @Override public String pageShow(String name) { //10,000 cycles for (int i = 0; i < 10000; i++) { } System.out.println("Database implementation paging"); return name; } }
3. Target Interface Class
public interface StudentService { /** * Sign in * @param name */ public void login(String name); /** * paging * @param name * @return */ public String pageShow(String name); }
4. Goal Achievement Class
public class StudentServiceImpl implements StudentService{ private StudentDao studentDao; public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; } @Override public void login(String name) { System.out.println("Logon Log"); studentDao.login(name); } @Override public String pageShow(String name) { System.out.println("Paging Log"); String s = studentDao.pageShow(name); return s; } }
5. Surround Notification
- Core method: Object proceed = methodInvocation.proceed(); Release
public class StudentAroundAdvice implements MethodInterceptor { /** * Parameter internal encapsulator's current proxy object method's parameters, execution methods, etc. * * @param methodInvocation * @return * @throws Throwable */ @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { //1. Control Transactions System.out.println("Controlling transactions"); //method Invocation method call System.out.println("Name of the current calling method" + methodInvocation.getMethod().getName()); //arguments parameter methodInvocation: method call System.out.println("The current parameters are:" + methodInvocation.getArguments()[0]); System.out.println("--------------"); //Record current time unit milliseconds long begin = System.currentTimeMillis(); System.out.println("Invoke Query Database"); //Let go, execute target method proceed: proceed on Object proceed = methodInvocation.proceed(); //Time unit milliseconds for end of recording long end = System.currentTimeMillis(); System.out.println("dao Time taken to execute" + (end - begin)); return proceed; } }
6. Delegate object creation rights to spring for target and tangent classes
<!--Administration dao assembly--> <bean id="studentDao" class="com.tjcu.dao.StudentDaoImpl"></bean> <!--Administration Service assembly/Target object--> <bean id="studentService" class="com.tjcu.service.StudentServiceImpl"> <!--Injection Value--> <property name="studentDao" ref="studentDao"></property> </bean> <!--Manage Notification Component--> <bean id="studentAroundAdvice" class="com.tjcu.advice.StudentAroundAdvice"></bean>
7. Configure weaving relationships and aop-related configurations in applicationContext.xml
<!--aop Related Configuration Faces=Tangent Point+Around Advice--> <aop:config> <!--breakthrough point execution:[eksɪˈkjuːʃn]implement--> <aop:pointcut id="pointcut" expression="execution(* com.tjcu.service.StudentServiceImpl.*(..))"/> <!--Assembly Cut advisor[ [ædˈvaɪzər]]: adviser advice-ref:notice pointcut-ref:breakthrough point--> <aop:advisor advice-ref="studentAroundAdvice" pointcut-ref="pointcut"></aop:advisor> </aop:config>
8. Test Code
@Test public void AroundAdviceTest() { //Start Factory ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/tjcu/Spring/ApplicationContext.xml"); //Get Component Target Object Is Proxy Object StudentService studentService = (StudentService) context.getBean("studentService"); //Call method, call target class through proxy class studentService.pageShow("Call target class through proxy class call"); }