相关阅读——Spring之AOP快速入门(xml配置文件)
1 官方AOP解释
AOP(Aspect Oriented Programming)称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想
2 个人理解的aop
用自己的话来说就比如一个人(A) 在排队,然后aop代理对象就相当于管理者,管理者就有权决定让他人(B)排任意位置的队,类比到程序里这个已经排队的人就是一个方法(目标对象)
而他人相当于切面对象;
管理者安排他人排队与否,如何排队就是配置织入(告诉框架哪些方法需要进行增强)
代码实现(注解方式)
目标对象(A)----要执行的方法
import org.springframework.stereotype.Component;
@Component("target")
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("排队ing-------");
}
}
切面对象(B)----要切入目标对象的方法
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("advice")
@Aspect
public class Advice {
@Before("execution(* com.aop..*.*(..))")
public void before() {
System.out.println("前面插队--------");
}
@After("execution(* com.aop..*.*(..))")
public void after1() {
System.out.println("后面插队--------");
}
}
xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.aop.jdk"></context:component-scan>
<!-- 自动代理-->
<aop:aspectj-autoproxy/>
</beans>
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AllTest {
@Autowired
private TargetInterface targetInterface;
@Test
public void test1(){
targetInterface.save();
}
}
一些注解
@Component(“xxx”)——没什么好说的
@Aspect——声明切面对象,即要切入的方法
@Before(“xxx”)——声明通知类型,也就是指定切面对象切入的时机,类似的还有after…
@ContextConfiguration(“xxx.xml”)——扫描配置文件
@RunWith(SpringJUnit4ClassRunner.class)——让测试在Spring容器环境下执行
谢谢阅读