pring Aop 日志管理
Spring 带给我们的另一个好处就是让我们可以“专心做事”,下面我们来看下面一个例子:
public void doSameSomesing(int age,String name){
// 记录日志
log.info(" 调用 doSameSomesing 方法,参数是: "+agfe+” ”+name);
// 输入合法性验证
if (age<=0){
throws new IllegalArgumentException("age 应该大于 0");
}
if (name==null || name.trim().equals("")){
throws new IllegalArgumentException("name 不能为空 ");
}
// 异常处理
try{ ...
service.save(age,name);// 业务处理存数据
}catch(...){
}catch(...){
}
// 事务控制
tx.commit();
}
大家想一下我们构建系统的主要目的是业务处理,但是我们在完成上面业务前需要解决如日志记录,参数验证等如此多方面的事情,这样的话留给我们考虑业务的时间就少了,使我们的业务代码质量得不到很好的保证,而这些方面又是不可缺少的我们不能不管,那么怎么办呢,我们能不能集中对这些方面进行一个统一的管理 ,当然可以,这就是 spring aop 要解决的问题。下面我们来看一个简单的例子,通过 spring aop 来集中解决日志方面的事情。
下面我们按照下面几个步骤去做:
1、 定义并实现对日志方面的处理。
package com.springaop.aop;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import org.springframework.aop.MethodBeforeAdvice;
public class LogAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object o)
throws Throwable {
System. out .println( " 系统日志: " +( new Date())+ ":" + " 调用了 " +method.getName()+ " : 使用了参数 " +(Arrays.toString (args)));
}
}
( 注意这里我们要实现 MethodBeforeAdvice 接口 指的是在方法执行前织入执行,类似还有 AfterReturningAdvice )
2、 定义业务代码
2.1 业务接口
package com.springaop.service;
public interface IAopMethod {
public void doSomesing(String name);
}
2.2 业务实现类
package com.springaop.service.impl;
import com.springaop.service.IAopMethod;
public class AopMethodimpl implements IAopMethod {
public void doSomesing(String name) {
System. out .println( "name:" +name);
}
}
3. 配置 applicationContext.xml.
<!-- 处理日志方面的 bean-->
< bean name = "mylogadvice" class = "com.springaop.aop.LogAdvice" ></ bean >
<!-- 处理业务的 bean-->
< bean name = "aopmethodtarget" class = "com.springaop.service.impl.AopMethodimpl" ></ bean >
<!-- 将日志 bean 和业务 bean 通过代理的方式进行代理整合 -->
< bean name = "aopmethod" class = "org.springframework.aop.framework.ProxyFactoryBean " >
< property name = "interceptorNames" >
< list >
< value > mylogadvice </ value >
<!-- 此处还可以放置多个处理方面的 bean-->
</ list >
</ property >
< property name = "target" ref = "aopmethodtarget" ></ property >
</ bean >
(这里可能大家对代理不是很清楚,我个人认为是把两个类或多个类方法进行合并执行,
大家通过观察我们的执行结果可以明白,高手不要见笑!)
4. 测试类
package com.springaop.service.impl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springaop.service.IAopMethod;
public class test {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext( "applicationContext.xml" );
IAopMethod method=(IAopMethod)context.getBean( "aopmethod" );
method.doSomesing( " zhangsan " );
}
}
运行结果是:
系统日志: Fri Sep 24 12:45:24 CST 2010: 调用了 doSomesing : 使用了参数 [zhangsan]
hello: zhangsan