Spring之切面变成(动态代理)_独立

本文详细介绍了如何在Java环境下使用AOP(面向切面编程)来增强转账服务的功能,包括前置通知、后置通知、异常通知和最后通知的实现过程。通过Spring框架的配置,将增强类与目标类进行关联,实现对业务逻辑的无侵入式扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:目标类

//dao
package it.heima.aspectj;

public class AccoutDao {
    public void out(String name,Double monney){
        System.out.println(name+"成功转出"+monney);
    }

    public void in (String name,Double monney){
        System.out.println(name+"成功转入"+monney);
    }
}

//service

package it.heima.aspectj;

public class AccountService {

    private AccoutDao accoutDao;
    public void setAccoutDao(AccoutDao accoutDao){
        this.accoutDao=accoutDao;
    }

    public void transfer(String name1,String name2,Double monney){
        accoutDao.out(name1,monney);
        int num=1/0;
        accoutDao.in(name2,monney);
    }
}

第二步:增强类

package it.heima.aspectj;

import org.aspectj.lang.JoinPoint;

public class MyAspect02 {
    //前置通知
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知");
    }
    //后置通知
    public void afterReturning(JoinPoint joinPoint,Object Result){
        System.out.println("后置通知");
    }
    //异常通知
    public void afterThrowning(JoinPoint joinPoint,Exception ex){
        System.out.println("异常通知,回滚,异常原因:"+ex);
    }
    //最后通知
    public void after(JoinPoint joinPoint){
        System.out.println("释放资源");
    }

}


第三步:applicationContext.xml配置

<!--配置Dao层-->
<bean id="accoutDao" class="it.heima.aspectj.AccoutDao"></bean>

<!--配置service层-->
<bean id="accountService" class="it.heima.aspectj.AccountService">
    <property name="accoutDao" ref="accoutDao"/>
</bean>
<!--配置增强类(单独)-->
<bean id="myAspect02" class="it.heima.aspectj.MyAspect02"></bean>
<!--让增强类和普通类产生关系-->
<aop:config proxy-target-class="false">
    <aop:pointcut id="mypointcut" expression="bean(*Service)"/>
 <aop:aspect ref="myAspect02">
                <aop:before method="before" pointcut-ref="mypointcut"/>
                <aop:after-returning method="afterReturning" pointcut-ref="mypointcut" returning="Result"/>
                <aop:after-throwing method="afterThrowning" pointcut-ref="mypointcut" throwing="ex"/>
                <aop:after method="after" pointcut-ref="mypointcut"/>
            </aop:aspect>
        </aop:config>
</beans>

第四步:测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")

public class AccountServiceTest {
    @Value("#{accountService}")
    private AccountService accountService;

    @Test
    public  void test(){
        accountService.transfer("aaa","bbb",100.0);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值