AOP 面向切面的编程
要明确下面几个概念
切面(Aspect):用于组织多个增强处理Advice,Advice放在切面中定义;
增强处理(Advice):切入点处执行增强处理
连接点(Joinpoint):程序执行过程中的点,如方法调用,异常抛出
切入点(Pointcut):可以插入增强处理的连接点
步骤:
1. Beans.xml中配置,启动@AspectJ支持
<context:component-scan base-package="com.jason.bookparadise.aspect"> <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/> </context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
2. 配置切面类,使用@Aspect
@Aspect public class TestAspect { @Before("execution(* com.jason.bookparadise.service.TestService.*(..))") public void testBefore(){ System.out.println("Test AOP Before Run"); } }
3. 定义增强处理
@Before,@After,@Around ("execution(* org.crazyit.app.service.impl.*.*(..)")
@AfterReturning (returning="rvt", pointcut="execution(* org.crazyit.app.service.impl.*.*(..)")
@AfterThrowing (throwing="ex", pointcut="* org.crazyit.app.service.impl.*.*.(..)")
可以通过JoinPoint来获取参数
4. 定义切入点
可以通过切面类对切入点重命名
@Aspect public class SystemArchitecture{ @Pointcut("execution(* org.crazyit.app.service.impl.*.*(..))") public void myPoint(){} }
调用时
pointcut="SystemArchitecture.myPointcut()"
实际应用中可以把所有的切点集中写到一个类中。
Log4j配置
Log分为root log和自定义log两种,Root log log4j.rootLogger=stdout, logfile, errorlogfile, 自定义log edit_delete_log.
关于Log文件的配置博文 http://www.cnblogs.com/ITtangtang/p/3926665.html 讲的很详细,可以参照。
private static Log logger = LogFactory.getLog("edit_delete_log");
logger.info(userid + " delete Book" + bookid + " " + rvt);
# Configure logging for testing: optionally with log file log4j.rootLogger=stdout, logfile, errorlogfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Append = true log4j.appender.stdout.Threshold = WARN log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=F:/BookParadise/Logs/root.log log4j.appender.logfile.Append = true log4j.appender.logfile.Threshold = WARN log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.errorlogfile=org.apache.log4j.FileAppender log4j.appender.errorlogfile.File=F:/BookParadise/Logs/runerror.log log4j.appender.errorlogfile.Append = true log4j.appender.errorlogfile.Threshold = ERROR log4j.appender.errorlogfile.layout=org.apache.log4j.PatternLayout log4j.appender.errorlogfile.layout.ConversionPattern=%d %p [%c] - %m%n log4j.logger.edit_delete_log = DEBUG, loglevel log4j.appender.loglevel=org.apache.log4j.FileAppender log4j.appender.loglevel.File=F:/BookParadise/Logs/edit_delete.log log4j.appender.loglevel.layout=org.apache.log4j.PatternLayout log4j.appender.loglevel.layout.ConversionPattern=%d %p [%c] - %m%n