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();
}

猜你喜欢

转载自ithuplion.iteye.com/blog/2372855