Spring AOP基于xml,注解

简介

Spring中有一个关键的组件AOP框架,然而Spring IOC容器并不依赖与AOP,也就是说可以不用AOP,他只是对项目的解耦更加细致,明确

AOP-另一种编程思想

当我们需要对分散的对象引入公共行为的时候,OOP并不能解决这个问题,也就是说,OOP允许实现从上到下,不适合从左到右的关系,它作为一种横切的技术,解刨开对象的内部,将那些与业务无关,却被业务模块共同调用或责任封装起来.

实现:

基于xml

1.创建目标对象

public class Target implements TargetInterface {
    @Override
    public void save() {
        System.out.println("save running");
    }
}

2.创建切面对象

public class MyAspect {

    public void brfore(){
        System.out.println("前置增强....");
    }
    public void afterReturning(){
        System.out.println("后置增强");
    }
    //ProceedingJoinPonit:正在执行的连接点=切点
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强");
        Object proced=pjp.proceed();//切点方法
        //切点方法
        System.out.println("环绕后增强");
        return proced;
    }
    public void afterThrowing(){
        System.out.println("异常抛出");
    }

创建ApplicationContext.xml声明Bean,和切面

 <!--目标对象 -->
    <bean id="target" class="aop_1.Target"/>

    <!--切面对象 -->
    <bean id="myAspect" class="aop_1.MyAspect"/>

    <!--配置织入:告诉spring框架 那些方法需要切入( 增强) -->
    <aop:config>
        <!--声明切面 -->
        <aop:aspect ref="myAspect">
            <aop:before method="brfore" pointcut="execution(public void aop_1.Target.save())" ></aop:before>
            <aop:around method="around" pointcut="execution(public void aop_1.Target.save())"></aop:around>
            <aop:after-throwing method="afterReturning" pointcut="execution(public void aop_1.Target.save())"></aop:after-throwing>
        </aop:aspect>
    </aop:config>

测试实现:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:Application.xml")
public class AopTest_1 {
    @Autowired
    private TargetInterface target;

    @Test
    public void test1(){
        target.save();
    }

}

 

从这个流程可以很直观的看出基于spring容器,很简单的实现了增强操作.而注解只是稍加改变好一点.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值