spring Aop的一个demo

面向切面是什么我就不说了.

上代码:

package com.foreveross.service.weixin.test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {
String name();
}
package com.foreveross.service.weixin.test;

import org.springframework.stereotype.Service;

@Service
public class DemoService { @Action(name="注解拦截操作...,这个是add操作...")
public void addDemo(){ }
}
package com.foreveross.service.weixin.test;

import org.springframework.stereotype.Service;

@Service
public class Demo1Service {
@Action(name="addDemo1的日志")
public void addDemo1(){ }
}
package com.foreveross.service.weixin.test;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component; @Aspect
@Component
public class LogAspect { @Pointcut("@annotation(com.foreveross.service.weixin.test.Action)")
public void annotationPointCut(){} @Before("execution(* com.foreveross.service.weixin.test.*.*(..))")
public void before(JoinPoint joinPoint){
MethodSignature signature=(MethodSignature)joinPoint.getSignature();
Method method=signature.getMethod();
System.out.println("方法规则式拦截:"+method.getName());
}
@After("annotationPointCut()")
public void after(JoinPoint joinPoint){
MethodSignature signature=(MethodSignature)joinPoint.getSignature();
Method method=signature.getMethod();
Action action=method.getAnnotation(Action.class);
System.out.println("注解式拦截..."+action.name());
}
}
package com.foreveross.service.weixin.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration
@ComponentScan("com.foreveross.service.weixin.test")
@EnableAspectJAutoProxy//注解开启Spring对AspectJ的支持
public class AppConfig { }
package com.foreveross.service.weixin.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {

    public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);
DemoService demo=context.getBean(DemoService.class);
Demo1Service demo1=context.getBean(Demo1Service.class);
demo.addDemo();
demo1.addDemo1();
context.close();
}
}
上一篇:PHP环境搭配


下一篇:C# Linq to SQL — Group by