spring aop学习1:演示代码(通过注解方式匹配切入方法)

来源:互联网 发布:网易邮箱泄露 数据库 编辑:程序博客网 时间:2024/05/17 03:27

1.搭建spring框架,添加开启aop注解的配置

2.新建java注解
AspectAnnotation.java:

package com.tiglle.manage.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface AspectAnnotation {}

3.新建切面类
TestAspect .java

package com.tiglle.manage.aspect;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect@Componentpublic class TestAspect {    @Pointcut("@annotation(com.tiglle.manage.annotation.AspectAnnotation)")    public void test(){    }    @Before("test()")    public void execTest(){        System.out.println("我是切面方法...");    }}

4.测试类

package com.tiglle.manage.test;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.tiglle.manage.annotation.AspectAnnotation;import com.tiglle.manage.service.TestService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath*:applicationContext*.xml"})public class AspectTest {    @Autowired TestService testService;    @Test    @AspectAnnotation    public void test(){        testService.test();    }}

6.输出结果

我是切面方法...我是TestService的test方法
阅读全文
0 0