spring aop编程

从spring容器获得目标类,如果配置aop,spring将自动生成代理。
要确定目标类,aspectj 切入点表达式,导入jar包
spring-framework-3.0.2.RELEASE-
dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE
1.目标类
public interface UserService {

public void addUser();
public void updateUser();
public void deleteUser();
}
2.切面类
/**
* 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
* * 采用“环绕通知” MethodInterceptor
*
*/
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyAspect implements MethodInterceptor{
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("开启事务");
//手动执行目标方法
Object obj = mi.proceed();
System.out.println("提交事务");
return obj;
}
}
3.spring配置
<!-- 1 创建目标类 -->
<bean id="userService" class="cn.ithuplion.spring_aop.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspect" class="cn.ithuplion.spring_aop.MyAspect"></bean>
<!-- 3 aop编程
3.1 导入命名空间
3.2 使用 <aop:config>进行配置
proxy-target-class="true" 声明时使用cglib代理
<aop:pointcut> 切入点 ,从目标对象获得具体方法
<aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
advice-ref 通知引用
pointcut-ref 切入点引用
3.3 切入点表达式
execution(* com.itheima.c_spring_aop.*.*(..))
选择方法 返回值任意 包 类名任意 方法名任意 参数任意

-->
<aop:config>
<aop:pointcut expression="execution(* 包名.*.*(..))" id="mypointcut"/>
<aop:advisor advice-ref="myAspect" pointcut-ref="mypointcut"/>
</aop:config>
4.测试
@Test
public void test1(){
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("cn/ithuplion/spring_aop/bean.xml");
UserService userService = (UserService)
applicationContext.getBean("userService");
userService.addUser();
userService.updateUser();
userService.deleteUser();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值