Spring AOP 30 minutes to master

Posted by siwelis on Fri, 21 Jan 2022 21:41:24 +0100

AOP introduction

Role and advantages of aop

Function: during the running of the program, enhance the function of the method without modifying the source code

(vernacular): dynamic code enhancement

Advantages: reduce duplicate code, improve development efficiency, and easy to maintain

(vernacular): it's easy to use

aop underlying implementation

The lower layer of AOP is realized through the dynamic proxy technology provided by Spring.

Spring dynamically generates proxy objects through dynamic proxy technology. When the proxy method is executed, it intervenes to call the methods of the target object to complete the function enhancement.

Dynamic agent based on JDK (as follows)

Target method interface

public interface TargetInterface {
    public void save();
}

Target method realization

public class Target implements TargetInterface {
    @Override
    public void save() {
        System.out.println("save running......");
    }
}

Enhancement method

public class Advice {

    public void before(){
        System.out.println("Pre enhancement...");
    }

    public void afterReturning(){
        System.out.println("Post enhancement...");
    }
}

test

public class ProxyTest {

    public static void main(String[] args) {
        //Create target object
        Target target = new Target();

        //Create enhancement object
        Advice advice =new Advice();


        TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.before();
                        method.invoke(target, args);
                        advice.afterReturning();
                        return null;
                    }
                });

        proxy.save();
    }
}

Dynamic agent based on cglib

Target method

public class Target {
    public void save() {
        System.out.println("save running......");
    }
}

Enhancement method

public class Advice {

    public void before(){
        System.out.println("Pre enhancement...");
    }

    public void afterReturning(){
        System.out.println("Post enhancement...");
    }
}

test

public class ProxyTest {

    public static void main(String[] args) {
        //Create target object
        Target target = new Target();

        //Create enhancement object
        Advice advice =new Advice();

        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(Target.class);

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                advice.before();
                Object invoke = method.invoke(target, args);
                advice.afterReturning();
                return invoke;
            }
        });
        Target proxy = (Target) enhancer.create();

        proxy.save();
    }
}

Implementing aop with xml

① Import coordinates

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.8</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.

② Create target interface and target class

Target interface

public interface TargetInterface {    public void save();}

Goal realization class

public class Target implements TargetInterface {    @Override    public void save() {        System.out.println("save running......");    }}

③ Create facet class (enhancement method class)

public class MyAspect {    public void before(){        System.out.println("Pre enhancement....");    }    public void afterReturning(){        System.out.println("Post enhancement...");    }}

④ Spring management

1. Create ApplicationContext xml

‖. Leave the object to Spring management

<!--Target object-->
<bean id="target" class="link.zishu.aop.Target"/><!--Tangent object--><bean id="myAspect" class="link.zishu.aop.MyAspect"/>

⑤ Configure the weaving relationship in the configuration file

<!--Configuration weaving, tell spring frame,What methods(Tangent point)What enhancements are needed(Front,Post enhancement)-->
<aop:config>    
	<!--Declaration section-->
	<aop:aspect ref="myAspect">        
		<!--section= Tangent point + notice-->        
		<!--pointcut="execution(public void link.zishu.aop.Target.save())"/>-->        <aop:before method="before" pointcut="execution( * link.zishu.aop.Target.save())"/>        <aop:after-returning method="afterReturning" pointcut="execution(* link.zishu.aop.Target.save())"/>
	</aop:aspect>
</aop:config>

⑥ Testing

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {    
	@Autowired    
	private TargetInterface target;    
	@Test    
	public void Test1(){
		target.save();    
	}
}

Implementing aop with annotations

① Create target interface and target class

Target interface

public interface TargetInterface {    public void save();}

Goal realization class

public class Target implements TargetInterface {    @Override    public void save() {        System.out.println("save running......");    }}

② Create facet class (enhancement method class)

public class MyAspect {    public void before(){        System.out.println("Pre enhancement....");    }    public void afterReturning(){        System.out.println("Post enhancement...");    }}

③ Spring management

Through the Component annotation, it is handed over to Spring for management

④ Using annotations to configure weaving relationships in facet classes

Different enhancements are configured through different annotations. For example: pre enhancement @ Before post enhancement @ AfterReturning

@Before("execution(* link.zishu.anno.Target.save())")
public void before(){    
	System.out.println("Pre enhancement....");
}

⑤ Turn on the automatic agent for component scanning and AOP in the configuration file

<!--Enable annotation scanning -->
<context:component-scan base-package="link.zishu.anno"/>
<!--aop Automatic proxy for-->
<aop:aspectj-autoproxy />

⑥ Testing

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoTest {    
	@Autowired    
	private TargetInterface target;    
	@Test    
	public void Test1(){        
		target.save();    
	}
}

Enhanced classification

Method nameMethod nameexplain
Before advice @BeforeNotify before calling method
Post notification@After-returningNotification after method invocation (when method execution is successful)
Around Advice @AroundSome customized operations before and after method call
Exception notification@After-throwingNotify after calling a method (when the method throws an exception)
Final notice@AfterNotification after a method is called, regardless of the method execution state

Topics: Java