Spring AOP 学习笔记 SpringAOP 面向切面编程, 主要用于日志,抽象统一的操作处理,以AOP的方式存放,利于代码扩展,维护。降低与核心业务逻辑的耦合。 主要概念:切面 , 切点, Spring AOP 实例代码: 基于注解的实例: 该实例写一个简单的计算类 , 在计算的前后输出日志。 必要的AOP JAR包 Spring Jar包 。 计算类接口规范
package com.test.Aop.demo1
public Interface Add
{
public int add(int a ,int b );
}
计算类的实现
package com.test.Aop.demo1
public class AddImpl implements Add
{
public int add(int a ,int b )
{
return a+b ;
}
}
切面类实现日志功能相当于代理对象
package com.test.Aop.demo1
@component
@Aspect
public class LoggingAspject
{
@Before("execution(public int com.test.Aop.demo1 .AddImpl .add (int,int))")
public void beforeMethod(JoinPoint joinpoint )
{
String methodName = joinpoint. getSignature().getName();
List<Object> methodargs = Arrays.asList(joinpoint.getArgs);
System.out.println("The method "+methodName+"begin add with args "+methodargs);
}
}
application-spring.xml 配置文件
<!--自动扫描-->
<context:component-scan base-package ="com.test.Aop.demo1"></context:component-scan>
<!-- 自动创建代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
Main 方法 程序入口
package com.test.Aop.demo1
public class Main
{
public static void main(String [] args )
{
ApplicationContext apcxt = new ClassPathXmlApplicationContext("application-spring.xml");
Add addimpl = apcxt.getBean(Add.class);
int result = addimpl. add(3,5);
System.out.println(result);
}
}