• 使用注解定义增强


    实现步骤:

      a.在项目中添加Spring AOP相关的jar文件

      b.只用注解定义前置增强和后置增强实现日志功能

      c.编写Spring配置文件,织入注解定义的增强

    1.定义增强类

     1 package com.aop;
     2 
     3 import org.apache.log4j.Logger;
     4 import org.aspectj.lang.annotation.AfterReturning;
     5 import org.aspectj.lang.annotation.Aspect;
     6 import org.aspectj.lang.annotation.Before;
     7 
     8 /**
     9  * 
    10  * @author Mr
    11  * 使用注解
    12  */
    13 @Aspect
    14 public class UserBizLogger {
    15     private static final Logger log = Logger.getLogger(UserBizLogger.class);
    16     //前置增强  com.biz.IUserBiz表示接口全类名
    17     @Before("execution(* com.biz.IUserBiz.*(..))")
    18     public void before(){
    19         log.info("即将调用业务逻辑方法!!");
    20     }
    21     //后置增强
    22     @AfterReturning("execution(* com.biz.IUserBiz.*(..))")
    23     public void afterReturing(){
    24         log.info("调用业务逻辑方法完毕!!");
    25     }
    26 }

    2.spring配置文件

    1 <bean id="dao" class="com.dao.impl.IUserDaoImpl"></bean>
    2     <bean id="biz" class="com.biz.impl.IUserBizImpl">
    3         <property name="dao" ref="dao"></property>
    4     </bean>
    5     <!-- 定义包含注解的增强类的实例 -->
    6     <bean class="com.aop.UserBizLogger"></bean>
    7     <!-- 织入使用注解定义的增强,需要引入AOP命名空间 -->
    8     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    3.测试类

     1 package com.test;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 import com.biz.IUserBiz;
     6 import com.domain.User;
     7 
     8 /**
     9  * 
    10  * @author Mr
    11  * aop测试类
    12  */
    13 public class Test {
    14 
    15     public static void main(String[] args) {
    16         //解析配置文件
    17         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    18         
    19         IUserBiz biz = (IUserBiz) ac.getBean("biz");
    20         User user = new User();
    21         user.setUname("小老虎");
    22         biz.save(user);
    23     }
    24 
    25 }

    4.测试效果

  • 相关阅读:
    五子棋
    纯ASP实现的“无刷新”聊天室
    砸砖块
    ASP.NET中批量插入数据
    判断一个dataset的数据是否包含另一个dataset的数据
    使用DB2时的一些问题
    RTOS,什么是硬实时和软实时
    异或运算^的一个作用
    vc 重启和关机
    About DLL
  • 原文地址:https://www.cnblogs.com/myhzb/p/7537927.html
Copyright © 2020-2023  润新知