Spring的Aop实现方式

Spring的Aop学习:首先需要到Spring的需要的jar:!

[注意需要导入commons-logging的jar不然spring测试会出现错误]


在学习的Aop的时候需要到图片中的框住的jar的!

实现Aop的方法之一:实现接口编写Aspect(切面实现前置通知方法implements MethodBeforeAdvice)

public class Log implements MethodBeforeAdvice{

@Override

public void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(target.getClass().getName()+"的"+method.getName()); } }`

编写接口和实现类;

在Spring的IOC容器里配置切面和目标类/

<!-- target目标类(代理的类) -->

<beanid="userService"class="cn.xst.service.UserServiceImpl"></bean>

<!-- 前置切面 -->

<beanid="log"class="cn.xst.log.Log"></bean>

<!-- 把切面和目标类 -->

<aop:config><!-- 切入点 -->

<aop:pointcut expression="execution(* cn.xst.service.impl.*.*(..))" id="pointcut"/>

<!-- 把切面和切入点织入 -->

<aop:advisoradvice-ref="log"pointcut-ref="pointcut"/></aop:config>

编写测试类:```

ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");

UserService userService=app.getBean(UserService.class);

userService.add();输出的结果:cn.xst.service.UserServiceImpl的add增加用户

配置后置通知且切面:

public class AfterLog implements AfterReturningAdvice {

@Override

public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {

System.out.println(target.getClass().getName()+"的"+method.getName());

}

在bean中配置切面:

<!-- 后置切面 -->

<beanid="afterlog"class="cn.xst.log.AfterLog"></bean>

<aop:config></aop:config><!-- 把切面和切入点织入 -->

<aop:advisoradvice-ref="afterlog"pointcut-ref="pointcut"/>

修改织入的advice-ref进行测试得到结果:修改用户cn.xst.service.impl.UserServiceImpl的update

第二种实现Aop切面的编程:(自定义)

public class Log {

public void before(){

System.out.println("-----方法执行前--------");

}

public void after(){

System.out.println("-----方法执行后--------");

}}

需要在Spring的IOC容器中配置:

<!-- target目标类(代理的类) -->

<beanid="userService"class="cn.xst.service.impl.UserServiceImpl"></bean>

<!-- 前置切面 -->

<beanid="log"class="cn.xst.log.Log"></bean>

<!-- 把切面和目标类 -->

<aop:config>

<aop:aspectref="log">

<aop:pointcut expression="execution(* cn.xst.service.impl.*.*(..))" id="pointcut"/>

<aop:beforemethod="before"pointcut-ref="pointcut"/>

<aop:aftermethod="after"pointcut-ref="pointcut"/>

</aop:aspect>

</aop:config>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值