Spring AOP

Aspect-oriented Programming:面向切面编程——分离方面集中实现,独立编写业务代码、方面代码,最后织入系统

基于代理类ProxyFactoryBean的AOP实现:

org.springframework.aop.framework.ProxyFactoryBean

ProxyFactoryBean属性:target(代理的目标对象)、proxyInterfaces(代理索要实现的接口)、interceptorNames(需要织入到目标对象的Bean的列表)、singleton(返回的代理是否是单实例,默认单实例)。

例:

编写方面代码:建com.shw.aop包,建LogAdvice类,继承MethodBeforeAdvice接口。

package com.shw.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

import org.apache.log4j.Logger;

public class LogAdvice implements MethodBeforeAdvice{

private Logger logger=Logger.getLogger(LogAdvice.class);

@Override

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

String targetClassName=target.getClass().getName();

String targetMethodName=method.getName();

String logInfoText="前置通知:"+targetClassName"+"类的"+"targetMethodName"+"方法开始执行";

logger.info(logInfoText);

}

}

上述代码使用了Logger完成日志功能,因此src下添加属性文件log4j.properties.

日志文件的配置可以参考另外两遍不错的博文,地址:

http://blog.csdn.net/qq_30175203/article/details/52084127

http://blog.csdn.net/edward0830ly/article/details/8250412


将业务逻辑代码和方面代码组装进代理类:

applicationContext.xml配置文件中:

①定义需要被织入通知的业务Bean——<bean id="userBiz" class="com.shw.biz.UserBizImpl"><property name="userDAO"·····

②定义切面通知——<bean id="logAdvice" class="com.shw.aop.LogAdvice"></bean>

③定义代理类——<bean id="ub" class="org.springframework.aop.framework.ProxyFactoryBean">

指定代理接口——<property name="proxyInterfaces"><value>com.shw.biz.UserBiz</value></property>

指定通知——<property name="interceptorNames"><list><value>logAdvice</value></list></property>

指定目标对象——<property name="target" ref="userBiz"></property>

ProxyFactoryBean是spring框架AOP中的代理组件类,用户通过这个代理类访问原来的Bean时,能保证在方法调用时自动执行通知的代码。

测试类:AOPTest.java

package com.springtest1;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.shw.biz.UserBiz;

public class AOPTest{

public static void main(String[] args){

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

UserBiz userBiz=(UserBiz)context.getBean("ub");

userBiz.addUser("zhangsan","123");

}

}

控制台输出:

[INFO ] [12:49:28] com.shw.aop.LogAdvice - 前置通知:com.shw.biz.UserBizImpl类的addUser方法开始执行
zhangsan用户添加成功


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值