Spring-aop 日志管理小例子

1,applicationContext.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:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 <context:annotation-config />
 <aop:aspectj-autoproxy />
 <context:component-scan base-package="com.sarkuya"/>
 
</beans>

 

2,bean里面的需要被做日志的方法

@Component(value="zhang")
public class AOPTest {
 public void save() {
  System.out.println("SpringAOP Test!");
 }
}

 

3,aop

@Aspect()
@Component
public class SampleAspect {

 @Before("execution(* com.sarkuya.service..*.*(..))")
 public void doBeforeInServiceLayer() {
  System.out.println("=====================================");
  System.out.println("Aop: do before in Service layer");
  System.out.println("=====================================");
 }
}

4, 如果需要拦截方法做一些检查

@Aspect()
@Component
public class Log {

 @Around("execution(* com.huayu.ww.dao.impl.LoginDAOimpl.CheckUser(..))")
 public TUser checkLogin(ProceedingJoinPoint pjp) {
    Object args[] = pjp.getArgs();
    System.out.println("log4j:" + args[0] + ""+ args[1]);
    try {
     TUser user = (TUser)pjp.proceed();
     return user;
  } catch (Throwable e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
   }
  return null;
 }
}

 

 

你可能感兴趣的:(AOP,log4j,user,service,Class,encoding)