1.service接口
package spring.service.service2;
public interface Service1 {
public void add();
public void del();
}
2.service实现类
package spring.service.service2;
public class Service1Imp implements Service1 {
@Override
public void add() {
System.out.println("添加用户");
/*int a=1/0;*/
}
@Override
public void del() {
System.out.println("删除用户");
}
}
4.切面类
package spring.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
public class Aspect_2 {
public void before(){
System.out.println("现在使用前置方法");
}
public void after(){
System.out.println("现在使用后置方法");
}
public Object round(ProceedingJoinPoint point) throws Throwable {
System.out.println("在方法前使用环绕方法");
Object proceed = point.proceed();
System.out.println("在方法之后调用环绕方法");
return proceed;
}
public void warning(JoinPoint joinPoint ,Throwable e){
System.out.println("现在使用异常方法"+e.getMessage());
}
}
5.jar包

6.beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--xmlns xml namespace:xml命名空间-->
<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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--声明被代理类-->
<bean id="Service" class="spring.service.service2.Service1Imp"></bean>
<!--声明切面方法-->
<bean id="Aspect" class="spring.Aspect.Aspect_2"></bean>
<!--使用AspectJ 去创造代理-->
<aop:config>
<!--声明切面类-->
<aop:aspect ref="Aspect">
<!--声明入口-->
<aop:pointcut id="point_cut" expression="execution(* spring.service.service2.Service1Imp.add())"></aop:pointcut>
<aop:before method="before" pointcut-ref="point_cut"></aop:before>
<aop:after method="after" pointcut-ref="point_cut"></aop:after>
<!--环绕方法-->
<aop:around method="round" pointcut-ref="point_cut"></aop:around>
<!--异常方法-->
<aop:after-throwing method="warning" pointcut-ref="point_cut" throwing="e"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
7.测试类
package spring.test;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.service.service2.Service1;
public class Test7 {
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans13.xml");
Service1 service1= (Service1) context.getBean("Service");
service1.add();
}
}
8.结果
现在使用前置方法
在方法前使用环绕方法
添加用户
在方法之后调用环绕方法
现在使用后置方法
9.感想
(1)spring这个容器对代理模式封装的还是很好的,轻松易懂
(2)注意环绕方法和异常方法对输入参数是有要求的
本文详细介绍了Spring框架中AOP(面向切面编程)的实际应用,包括定义Service接口及其实现类,创建切面类,配置beans.xml进行AOP代理,并通过测试类验证结果。展示了前置、后置、环绕和异常通知的使用。
3010

被折叠的 条评论
为什么被折叠?



