导论:为了系统维持和排查错误的需要,有时我们需要程序自动的写日志,将用户的操作记录下来。在这里,可以使用Spring的AOP技术。我们可以写一个切面,并且指定切入的范围(切入点),当系统运行后,日志信息将可以自动记录在指定的文件或数据库中。流程:1、定义切面(Log4jHandlerAOP类,它包含记录信息的内容)--->2、指定日志输出方式和输出目的地(log4j.properties)---->3、写配置文件(aop-schema.xml),指定切面作用的范围。代码:1. 定义切面(Log4jHandlerAOP类,它包含记录信息的内容)import org.apache.log4j.Logger;import org.aspectj.lang.ProceedingJoinPoint;public class Log4jHandlerAOP { Logger logger; public Object RecordLog(ProceedingJoinPoint pjp) throws Throwable { logger = Logger.getLogger(Log4jHandlerAOP.class); String className = pjp.getTarget().getClass().getSimpleName(); String methodName = pjp.getSignature().getName(); String userName = "徐亮"; StringBuffer sb = new StringBuffer(); sb.append("userName: " + userName); sb.append(" className: " + className); sb.append(" methodName: " + methodName); logger.info(sb.toString()); Object obj = pjp.proceed(); return obj; }}2. log4j.properties (指定日志输出方式和输出目的地) //"og4j.rootLogger"右边可以指定输出信息的级别,如DEBUG或INFO或ERROR等。//"log4j.appender.file.File"指定输出到特定的文件下。log4j.rootLogger=DEBUG,file,consolelog4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=D/://aop.loglog4j.appender.file.layout=org.apache.log4j.SimpleLayoutlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.layout=org.apache.log4j.SimpleLayout3. 写配置文件(aop-schema.xml),指定切面作用的范围<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="log4jHandlerAOP" class="myLog.Log4jHandlerAOP"></bean> <bean id="myService" class="myLog.MyService"></bean> <aop:config> <aop:aspect id="logAspect" ref="log4jHandlerAOP"> <aop:pointcut id="logPointCut" expression="execution(* myLog.*.* (..))" /> <aop:around method="RecordLog" pointcut-ref="logPointCut" /> </aop:aspect> </aop:config></beans>4、目标类(MyService )public class MyService implements IMyService { public void regist(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("----执行注册操作----"); }}5、测试类public class myLogTest { public static void main(String[] args) { ApplicationContext ctx= new ClassPathXmlApplicationContext("myLog/aop-schema.xml"); IMyService myService=ctx.getBean("myService",IMyService.class); myService.regist(); }}---------------------------运行结果------------------------------------INFO - userName: 徐亮. className: MyService. methodName: regist----执行注册操作------------------------------------------------------------------------------