一.Spring Aop
1.1什么是AOP
1.2AOP的作用及其优势
作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,并且便于维护
1.3AOP的底层实现
实际上,AOP的底层是通过Spring提供的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象方法,从而完成功能的增强。
1.4AOP的动态代理技术
1.5AOP相关概念
1.6AOP开发明确的事项
二.基于XML的AOP开发
2.1快速入门
(1)导入坐标
(2)创建目标接口和目标类
接口
public interface TarGetInterface {
void save();
}
目标类
public class Target implements TarGetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
(3)
创建切面类
public class MyAspect {
public void before(){
System.out.println("前置增强...");
}
public void afterReturnning()
{
System.out.println("后置增强..");
}
}
(4)将目标类和切面类的对象创建权交给Spring
<!--目标对象-->
<bean id="target" class="com.itheima.aop.Target"></bean>
<!--切面对象-->
<bean id="myAspect" class="com.itheima.aop.MyAspect"></bean>
(5)在applicationContext.xml
<aop:config>
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:before>
<aop:after-returning method="afterReturnning" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after-returning>
</aop:aspect>
</aop:config>
(6)测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TarGetInterface target;
@Test
public void test1()
{
target.save();
}
}
2.2XML配置AOP详解
2.通知的类型
3.切点表达式的抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用Pointcut-ref属性来引用抽取后的切点表达式。
<aop:config>
<aop:aspect ref="myAspect">
<aop:pointcut id="myPointcut" expression="execution( * com.itheima.aop.*.*(..))"/>
<aop:after-returning method="afterReturnning" pointcut-ref="myPointcut"></aop:after-returning>
</aop:aspect>
</aop:config>
3.基于注解的AOP开法
3.1快速入门
(1)导入坐标
(2)创建目标接口和目标类
接口
public interface TarGetInterface {
void save();
}
目标类
public class Target implements TarGetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
(3)
创建切面类
public class MyAspect {
public void before(){
System.out.println("前置增强...");
}
public void afterReturnning()
{
System.out.println("后置增强..");
}
}
(4)(5)
用注解实现
目标类
@Component("target")
public class Target implements TarGetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
切面类
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面
public class MyAspect {
@Before("execution(* com.itheima.anno.*.*(..))")
public void before(){
System.out.println("前置增强...");
}
@AfterReturning("pointcut()")
public void afterReturnning()
{
System.out.println("后置增强..");
}
@Pointcut("execution(* com.itheima.anno.*.*(..))")
public void pointcut(){
}
}
<!--aop自动代理-->
<!--aop自动代理-->
<aop:aspectj-autoproxy/>
(6)测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoTest {
@Autowired
private TarGetInterface target;
@Test
public void test1()
{
target.save();
}
}
3.2注解配置AOP详解
- 注解通知的类型