使用注解定义增强

实现步骤:

  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.测试效果

 

转载于:https://www.cnblogs.com/myhzb/p/7537927.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值