illustrate
Spring uses enhanced classes to define horizontal logic, while Spring only supports method join points, and incremental classes also contain information on where to add cross-cutting code to the method. So the enhancement contains both the horizontal logic and the information of some connection points.
Types of
According to the position of the connection point of the enhancement in the target class method, it is divided into
- pre-enhancement
- rear boost
- Surround enhancement
- Exception throwing enhancement
- Referral enhancement
pre-enhancement
Scenario: The waiter provides 2 services: welcoming customers, serving customers
package com.jihite; public interface Waiter { void greetTo(String name); void serveTo(String name); }
The new arrivals are as follows
package com.jihite; public class NaiveWaiter implements Waiter{ @Override public void greetTo(String name) { System.out.println("Greet to " + name); } @Override public void serveTo(String name) { System.out.println("Serve to " + name); } }
The new waiter comes up to provide service, which is relatively vigorous. Before doing everything, he will say hello. The following defines the pre-enhanced class.
package com.jihite; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class GreetingBeforeAdvice implements MethodBeforeAdvice{ @Override public void before(Method method, Object[] args, Object obj) throws Throwable { String clientName = (String)args[0]; System.out.println("How are you! Mr." + clientName); } }
Configure in Spring
Define beans.xml in src/main/resources
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="greetingBeforeAdvice" class="com.jihite.GreetingBeforeAdvice"/> <bean id="targetBefore" class="com.jihite.NaiveWaiter"/> <bean id="waiterBefore" class="org.springframework.aop.framework.ProxyFactoryBean" p:interceptorNames="greetingBeforeAdvice" p:target-ref="targetBefore" p:proxyTargetClass="true" /> </beans>
test
public class BeforeAdviceTest { private Waiter target; private BeforeAdvice advice; private ProxyFactory pf; @BeforeTest public void init() { target = new NaiveWaiter(); advice = new GreetingBeforeAdvice(); pf = new ProxyFactory(); pf.setTarget(target); pf.addAdvice(advice); } }
result
How are you! Mr.Jphn Greet to Jphn How are you! Mr.Tom Serve to Tom
Other types of enhancement classes are similar to pre-enhancement, please refer to the code