Spring之AOP快速入门(注解)

相关阅读——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容器环境下执行

谢谢阅读
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值